Class: Rack::GeoIPCity

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/geoipcity.rb,
lib/rack/geoipcity/version.rb

Overview

See the README for more docs.

Examples:

use Rack::GeoIPCity, :db => "/PATH/TO/GeoLiteCity.dat")

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of GeoIPCity.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :db (String)

    Path to the GeoIP database

  • :ips (#ip) — default: 'Rack::Request.new(env)'

    An object that responds to ‘ip` and gives an IP address. You’ll probably want to use this when you’re developing/testing locally and want to pass in fake addresses to get the GeoIP to fire something other than blanks.

  • :path (Regexp)
  • :prefix (String)


28
29
30
31
32
33
34
35
36
# File 'lib/rack/geoipcity.rb', line 28

def initialize(app, options = {})
  options[:db] ||= 'GeoIP.dat'
  @ips           = options[:ips]
  @path          = ->(env){ env['PATH_INFO'].start_with? options[:prefix] } unless options[:prefix].nil?
  @path          = ->(env){ env['PATH_INFO'] =~ options[:path] } unless options[:path].nil?
  @path         ||= ->(_){ true }
  self.class.db  = GeoIP.new(options[:db])
  @app           = app
end

Class Method Details

.dbGeoIP

Use this from another app, say a Sinatra or Rack app, when you want to use the GeoIP database for something other than the referrer’s IP.

Returns:

  • (GeoIP)


19
20
21
# File 'lib/rack/geoipcity.rb', line 19

def self.db
  @db
end

.db=(db) ⇒ Object

Setting the db. Let the app do this, hands away!

Parameters:

  • :db (GeoIP)


12
13
14
# File 'lib/rack/geoipcity.rb', line 12

def self.db=( db )
  @db = db
end

Instance Method Details

#call(env) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rack/geoipcity.rb', line 38

def call(env)
  if @path.call(env)
    ips = @ips || Rack::Request.new(env)
    res = self.class.db.city ips.ip
    unless res.nil? # won't bork on local or bad ip's
      h = Hash[ [:country_code2, :country_code3, :country_name, :continent_code, :region_name, :city_name, :postal_code, :latitude, :longitude, :dma_code, :area_code, :timezone, :ip,].map{|x| [ "GEOIP_#{x.upcase}", res.__send__(x) ] } ].delete_if{|k,v| v.nil? }
      
      env.merge! h
    end 
  end      
  @app.call(env)
end