Using Rack GeoIPCity

I wanted to use rack-geoipcountryhttps://github.com/tma/rack-geoipcountry with the MaxMind City Lite database, but I was getting funny results. Turns out that the country and city databases return different structs. So, I forked the code and made this new gemhttps://rubygems.org/gems/rack-geoipcity, unimaginatively called Rack GeoIPCity.

First you’ll have to install the C APIhttp://www.maxmind.com/app/c. Then the geoip gemhttps://rubygems.org/gems/geoip:

gem install geoip

You might need to do something like:

gem install geoip -- --with-geoip-dir=/path/to/C-API

but only if you get into trouble, make sure you read the error messages!

Now install rack, rack-geoipcity; and sinatra for the examples below:

gem install rack rack-geoipcity sinatra

The layout of the directory holding the sinatra app is:

- appdir (call this whatever you like)
  - app.rb
  - config.ru
  - views
    - layout.haml


# encoding: UTF-8

require "sinatra/base"
require 'haml'

class GeoIPApp < Sinatra::Base

  configure do
    set :root, File.dirname( __FILE__ )

  get "/" do
    output = ''
    output << "<p>#{request.env.inspect}</p>"

end #class


# encoding: UTF-8

class Rack::ModifyIp
  def initialize( app )
    @app = app
  def call(env)
    req = Rack::Request.new(env)
    unless req.query_string.empty?
      env.merge!( {'REMOTE_ADDR' => req.query_string})

root = File.expand_path File.dirname(__FILE__)
require File.join( root , "app.rb" )
require "rack/geoipcity"

app = Rack::Builder.app do
  use Rack::ModifyIp
  use Rack::GeoIPCity, :db => "/usr/local/share/GeoIP/GeoLiteCity.dat"
  run GeoIPApp

run app

Notice the piece of Rack middleware I’ve chucked in at the top, that allows us to test it by using ip’s in the querystring. Also notice the path to the database, you should change that to wherever your database is (download it from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz)




Now you can run the following in a terminal:

  cd to_whatever_you_called_appdir
  rackup config.ru

and open your browser at http://localhost:9292/, and you should see the output of Rack’s environment, and REMOTE_ADDRESS is Now try:


Which should bring back results for Mountain View in the US, which is where Google are located. Try it with any ip you like.

Added on:
Last updated:
Info:My system at the time of writing: - OSX 10.6.7 - Ruby v1.9.2 - sinatra (1.2.6) - rack (1.3.0) - geoip (1.1.1) - rack-geoipcity (0.0.1)