Title
Rails 3 get country name from client ip in request object
Body

If you want to extract a user country name from visitors' IP addresses. Just do the following:--


1.)  in Gemfile:--  gem 'geoip'


2.) Download GeoIP.dat.gz from http://www.maxmind.com/app/geolitecountry. unzip the file. 


3.) Lets assume that the unzipped under #{RAILS_ROOT}/db dir.


4.) sample code :--


 

@geoip ||= GeoIP.new("#{RAILS_ROOT}/db/GeoIP.dat")    
remote_ip = request.remote_ip if remote_ip != "127.0.0.1" #todo: check for other local addresses or set default value
  location_location = @geoip.country(remote_ip)
  if location_location != nil     
    @model.country = location_location[2]
  end
end

Cheers 
Alok Anand
Rails Detective
Associated Tags
3, country, country name, geoip, geoip gem, geoip plugin, IP, Rails, Ruby
Created By
alokanand
Created At
2011-08-26 13:32:53 UTC
Last Updated At
2011-08-26 13:32:53 UTC
Add Comment