Class: SinaGeoIp

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

Constant Summary collapse

SERVICE_URL =
'http://int.dpool.sina.com.cn/iplookup/iplookup.php'
IPV4_REGEXP =
/\A(?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)(?:\.(?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)){3}\z/
@@timeout =
1
@@fallback_timeout =
3

Class Method Summary collapse

Class Method Details

.fallback_timeoutObject



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

def fallback_timeout
  @@fallback_timeout
end

.fallback_timeout=(fallback_timeout) ⇒ Object



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

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:

Example:

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


52
53
54
55
56
57
58
59
# File 'lib/sina_geoip.rb', line 52

def geolocation(ip, options={})
  location = nil
  Timeout.timeout(self.fallback_timeout) do
    parsed_response = JSON.parse RestClient::Request.execute(:method => :get, :url => lookup_url(ip, options), :timeout => self.timeout)
    location = to_j(parsed_response, options)
  end
  location
end

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



39
40
41
42
43
44
# File 'lib/sina_geoip.rb', line 39

def lookup_url(ip, options = {})
  set_defaults_if_necessary options
  raise 'Invalid IP address' unless ip.to_s =~ IPV4_REGEXP
  #http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=202.102.154.3
  "#{SERVICE_URL}?format=json&ip=#{ip}"
end

.set_defaults_if_necessary(options) ⇒ Object



32
33
34
35
36
37
# File 'lib/sina_geoip.rb', line 32

def set_defaults_if_necessary options
 args = [:country, :province,:city]
  if options[:precision] && !args.include?(options[:precision])
    raise 'Invalid precision.'  
  end
end

.timeoutObject



16
17
18
# File 'lib/sina_geoip.rb', line 16

def timeout
  @@timeout
end

.timeout=(timeout) ⇒ Object



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

def timeout= timeout
  @@timeout = timeout
end