Posts in rails

Using Ruby Geocoder Gem Locally

These days I have been needing test a small feature (for a personal project) related with Geolocalization. The first and most obvious option was used Geocoder which has a number features enough for what I’m needing.

Alright I already have settled the gem on my Gemfile, but How I can test this gem on my local environment? due to in the docs it’s clear when you use this Gem with a IP 0.0.0.0 the Geocoder::Result object is nil.

Fortunately there is a option at least I can figure out this one in order to sort out the previous issue and do test on local.

We’re going to use Rack middleware in order to mock the IP with a custom one.

Let’s create a file which we called it fake_ip.rb with following content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class FakeIp
  def initialize(app, ip)</p>

<pre><code>@app = app
@ip = ip
</code></pre>

<p>  end</p>

<p>  def call(env)</p>

<pre><code>env['HTTP_X_FORWARDED_FOR'] = nil
env['REMOTE_ADDR'] = env['action_dispatch.remote_ip'] = @ip
@status, @headers, @response = @app.call(env)
[@status, @headers, @response]
</code></pre>

<p>  end
end

The previous code is pretty simple, the interesting part is on call method which change the values for some of elements env.

In terms very simple The env variable is a hash. That hash contains a lot of useful information including request headers and body, as well as run-time environment data that may have been added by upstream middleware.

Now, edit config/application.rb and put:

1
config.middleware.use(&lsquo;FakeIp&rsquo;, &lsquo;187.16.144.141&rsquo;)

The previous code allow us to mock the IP with someone custom. Now if you visit a controller a inspect the content

1
2
3
4
5
puts request.location.country_code</p>

<h1>should see the country code for IP 187.16.144.141 <code>BR</code></h1>

<p>

I wrote a small rack-app in order to show you the whole workflow.

Do you know a better way to do this? Share it!

written in development, gems, geocoder, rails, ruby