Search code examples
ruby-on-railsherokuiprails-geocoder

Ruby geocoder on Heroku yields private IP address


Ruby Geocoder (http://rubygeocoder.com/) works fine for getting the latitude and longitude of a known address. Now I am trying to use it to look up a Country code by IP Address so that a new user won't have to select their country.

if @person.country.blank?
    ip_loc = Geocoder.search(my_ip_address)
    if ip_loc.present?
       @person.country = ip_loc[0].data['country_code']
    end
end

To get their IP address to feed Geocoder, I am using socket:

 def my_ip_address
    require 'socket'
    list=Socket.ip_address_list
    ip = list.detect{|intf| intf.ipv4_private?}
    ip.ip_address if ip
 end

Since IP lookup won't work for a development machine (IP address is always a private, internal number) I am trying to test this on Heroku.

When this runs on Heroku, however, I am still getting back a private IP address 172.19.75.142 which cannot be looked up with Geocoder.

Can someone steer me in a productive direction for getting Country from IP that will work on Heroku?


Solution

  • You can get the ip address of the user/client with request.remote_ip. You should then be able to feed this value into Geocoder.

    Note that request will only be available in your controllers.