Geolocation with MaxMind's GeoIP and the geoip-city RubyGem

Install GeoIP library --------------------- ```ruby wget tar -zxvf GeoIP.tar.gz cd GeoIP ./configure --prefix=/opt/GeoIP make && sudo make install ``` Install the geoip-city gem -------------------------- ```ruby gem install geoip_city -- --with-geoip-dir=/opt/GeoIP ``` Test the bindings ----------------- ```ruby curl -O gunzip GeoLiteCity.dat.gz ``` Fire up IRB and try the following code: ```ruby require 'rubygems' require 'geoip_city' db ='GeoLiteCity.dat') result = db.look_up('') p result ``` Another option is to use's database, as described in [this article]( Create a wrapper ---------------- ```ruby require 'rubygems' require 'geoip_city' require 'ostruct' class Location < OpenStruct end class GeoIP class << self DB ='GeoLiteCity.dat') def lookup(ip) if result = DB.look_up(ip) location = # # {:country_code=>"FR", :country_code3=>"FRA", :country_name=>"France", :latitude=>46.0, :longitude=>2.0} # result.each do |key, val| location.send "#{key}=", val end end location end end end ``` Add some Rails caching ---------------------- Combined with the above code this will give you cached IP lookups: ```ruby class GeoIP class << self def lookup_with_caching(ip) Rails.cache.fetch(ip, :expires_in => 1.month) do lookup_without_caching(ip) end end alias_method_chain :lookup, :caching end end ``` Alternatives ------------ If you're unable to install the C extension you might want to have a look at the geoip gem, which is a pure Ruby library that can read the MaxMind's geoip database. It's slower but easier to install: