Class: Rack::Geoip::Lookup

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/geoip/lookup.rb

Overview

Implements Rack’s middleware interface and provides the geoip lookup service

Constant Summary collapse

DEFAULT =
{:path => '/geoip/lookup', :db => 'GeoLiteCity.dat', :db_lookup => :memory}

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Lookup

Returns a new instance of Lookup.



10
11
12
13
# File 'lib/rack/geoip/lookup.rb', line 10

def initialize(app, options={})
  @app, @options = app, DEFAULT.merge(options)
  @db = GeoIPCity::Database.new(@options[:db], @options[:db_lookup])
end

Instance Method Details

#_call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rack/geoip/lookup.rb', line 19

def _call(env)
  if env['PATH_INFO'] == @options[:path]
    request = Rack::Request.new(env)
    if request.params['ip'] && result=@db.look_up(request.params['ip'])
      [200, {'Content-Type' => 'application/json'}, result.to_json]
    else
      [404, {'Content-Type' => 'text/plain'}, "Example usage: #{env['rack.url_scheme']}://#{env['HTTP_HOST']}#{env['PATH_INFO']}?ip=8.8.8.8"]
    end
  else
    @app.call(env)
  end
end

#call(env) ⇒ Object



15
16
17
# File 'lib/rack/geoip/lookup.rb', line 15

def call(env)
  dup._call(env)
end