I want to extract a user country name from visitors\' IP addresses.
I could get the IP address with remote_ip. But what could be
the easiest way to get
The geoip gem no longer works with the new MaxMind databases. There is a new gem that does this, MaxMind-DB-Reader-ruby.
Simply download the City or Country binary, gzipped databases from MaxMind, unzip, and use the following sort of code:
require 'maxmind/db'
reader = MaxMind::DB.new('GeoIP2-City.mmdb', mode: MaxMind::DB::MODE_MEMORY)
# you probably want to replace 1.1.1.1 with request.remote_ip
# or request.env['HTTP_X_FORWARDED_FOR']
ip_addr = '1.1.1.1'
record = reader.get(ip_addr)
if record.nil?
puts '#{ip_addr} was not found in the database'
else
puts record['country']['iso_code']
puts record['country']['names']['en']
end
reader.close
Adapt based on your needs. I created a method in an initializer which I can call as necessary.