Class: MMGeoip

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

Defined Under Namespace

Classes: NoDatabaseFile, NoIpGiven, Regions

Constant Summary collapse

FIELDS =
[:hostname, :ip, :country_code, :country_code3, :country_name,
:country_continent, :region, :city, :postal_code, :lat, :lng, :dma_code,
:area_code, :timezone]
VERSION =
'0.1.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ MMGeoip

Returns a new instance of MMGeoip.

Raises:



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

def initialize(env)
  # May be a Rack @env or any hash containing initial data. Or just an IP.
  @env = env.is_a?(Hash) ? env.dup : {:ip => env}
  @ip = @env[:ip] ||
    @env["HTTP_X_REAL_IP"] ||
    (@env["HTTP_X_FORWARDED_FOR"] && @env["HTTP_X_FORWARDED_FOR"].split(/[ ,]+/).first) ||
    @env["REMOTE_ADDR"]
  
  raise NoIpGiven.new("No IP in env hash") unless @ip
  raise NoDatabaseFile.new("No database file: #{self.class.db_path}") unless File.exists? self.class.db_path
end

Instance Attribute Details

#lookupObject (readonly)

Returns the value of attribute lookup.



14
15
16
# File 'lib/mm_geoip.rb', line 14

def lookup
  @lookup
end

Class Method Details

.data_pathObject



77
78
79
# File 'lib/mm_geoip.rb', line 77

def self.data_path
  File.join(File.dirname(File.expand_path(__FILE__)), '../data')
end

.db_pathObject



80
81
82
# File 'lib/mm_geoip.rb', line 80

def self.db_path
  @db_path || ENV['MMGeoipDatabase'] || File.join(data_path, 'GeoLiteCity.dat')
end

.db_path=(path) ⇒ Object



83
84
85
# File 'lib/mm_geoip.rb', line 83

def self.db_path=(path)
  @db_path = path
end

Instance Method Details

#geodbObject



31
32
33
# File 'lib/mm_geoip.rb', line 31

def geodb
  @geodb ||= GeoIP.new self.class.db_path
end

#get_from_env(field) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mm_geoip.rb', line 44

def get_from_env(field)
  # APACHE:GEOIP with Geolite City give us:
  # GEOIP_REGION, GEOIP_CITY, GEOIP_DMA_CODE, GEOIP_AREA_CODE, GEOIP_LAT, GEOIP_LNG
  # 
  # Nginx with HttpGeoIPModule and Geolite City makes these variables available in nginx.conf:
  # $geoip_country_code, ..., you'll have to set the env variables by yourself.
  # I'd recommend using the X_GEOIP_... form.
  # 
  # Here, we look for both forms and the plain version.
  # 
  @env[field] || @env["GEOIP_#{field.to_s.upcase}"] || @env["X_GEOIP_#{field.to_s.upcase}"]
end

#looked_up?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/mm_geoip.rb', line 61

def looked_up?
  !!@lookup
end

#region_nameObject



57
58
59
# File 'lib/mm_geoip.rb', line 57

def region_name
  country_code && MMGeoip::Regions[country_code.to_sym] && MMGeoip::Regions[country_code.to_sym][region]
end