Class: GeoIp

Inherits:
Object
  • Object
show all
Defined in:
lib/geo_ip.rb

Defined Under Namespace

Classes: ApiKeyError, InvalidIpError, InvalidPrecissionError, InvalidTimezoneError

Constant Summary collapse

SERVICE_URL =
'http://api.ipinfodb.com/v3/ip-'
CITY_API =
'city'
COUNTRY_API =
'country'
@@api_key =
nil
@@timeout =
1
@@fallback_timeout =
3

Class Method Summary collapse

Class Method Details

.api_keyObject



20
21
22
# File 'lib/geo_ip.rb', line 20

def api_key
  @@api_key
end

.api_key=(api_key) ⇒ Object



24
25
26
# File 'lib/geo_ip.rb', line 24

def api_key=(api_key)
  @@api_key = api_key
end

.fallback_timeoutObject



36
37
38
# File 'lib/geo_ip.rb', line 36

def fallback_timeout
  @@fallback_timeout
end

.fallback_timeout=(fallback_timeout) ⇒ Object



40
41
42
# File 'lib/geo_ip.rb', line 40

def fallback_timeout=(fallback_timeout)
  @@fallback_timeout = fallback_timeout
end

.geolocation(ip, options = {}) ⇒ Object

Retreive the remote location of a given ip address.

It takes two optional arguments:

  • preceision: can either be :city (default) or :country

  • timezone: can either be false (default) or true

Example:

GeoIp.geolocation('209.85.227.104', {:precision => :city, :timezone => true})


67
68
69
70
71
72
73
74
75
# File 'lib/geo_ip.rb', line 67

def geolocation(ip, options = {})
  location = nil
  Timeout.timeout(fallback_timeout) do
    parsed_response = JSON.parse Net::HTTP.get(URI(lookup_url(ip, options)))
    location = convert_keys(parsed_response, options)
  end

  location
end

.lookup_url(ip, options = {}) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/geo_ip.rb', line 51

def lookup_url(ip, options = {})
  set_defaults_if_necessary options
  fail ApiKeyError.new('API key must be set first: GeoIp.api_key = \'YOURKEY\'') if api_key.nil?
  fail InvalidIpError.new(ip) unless ip.to_s =~ Resolv::IPv4::Regex || ip.to_s =~ Resolv::IPv6::Regex

  "#{SERVICE_URL}#{options[:precision] == :city || options[:timezone] ? CITY_API : COUNTRY_API}?key=#{api_key}&ip=#{ip}&format=json&timezone=#{options[:timezone]}"
end

.set_defaults_if_necessary(options) ⇒ Object



44
45
46
47
48
49
# File 'lib/geo_ip.rb', line 44

def set_defaults_if_necessary(options)
  options[:precision] ||= :city
  options[:timezone] ||= false
  fail InvalidPrecisionError unless [:country, :city].include?(options[:precision])
  fail InvalidTimezoneError unless [true, false].include?(options[:timezone])
end

.timeoutObject



28
29
30
# File 'lib/geo_ip.rb', line 28

def timeout
  @@timeout
end

.timeout=(timeout) ⇒ Object



32
33
34
# File 'lib/geo_ip.rb', line 32

def timeout=(timeout)
  @@timeout = timeout
end