4

I'm trying to localize my users throught their IP address. As the docs say, a class method called geocode_ip_address has been mixed into the ActionController::Base. But there must be something I'm missing. Do I have to define a filter like this before_filter :geocode_ip_address to use it? (I want to know the location for every request done).

The documentation also talks about "A first-time lookup will result in the GeoLoc class being stored in the session as :geo_location" but I certainly don't have that key inside the session hash.

What am I doing wrong?

Thanks.

Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
Alex Epelde
  • 1,679
  • 1
  • 15
  • 16

1 Answers1

5

You don't need to prepend before_filter to geocode_ip_address, but rather just put that in your controller:

class YourController < ApplicationController
  geocode_ip_address

  def action
    if geo = session[:geo_location]
      # geo here is a Geokit::GeoLoc object
    end
  end
end

Note that if the geocoding fails geo will be nil. If you're running in development you'll be trying to geocode 127.0.0.1, so you'll want to set your remote_ip in the request object. I did so by adding this to the bottom of config/environments/development.rb:

class ActionDispatch::Request
  def remote_ip
    "x.x.x.x" # fill in your IP address here
  end
end
gjastrab
  • 88
  • 1
  • 5
  • I had seen other posts saying to use **session[:geo_location]**, but there is also a **retrieve_location_from_cookie_or_service** helper method that may be used. – gjastrab May 10 '11 at 19:45
  • Thanks, the ActionDispatch remote IP workaround was quite useful. – Alex Epelde May 11 '11 at 06:29