Class: SinaGeoIp
- Inherits:
-
Object
- Object
- SinaGeoIp
- 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
- .fallback_timeout ⇒ Object
- .fallback_timeout=(fallback_timeout) ⇒ Object
-
.geolocation(ip, options = {}) ⇒ Object
Retreive the remote location of a given ip address.
- .lookup_url(ip, options = {}) ⇒ Object
- .set_defaults_if_necessary(options) ⇒ Object
- .timeout ⇒ Object
- .timeout=(timeout) ⇒ Object
Class Method Details
.fallback_timeout ⇒ Object
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, ={}) location = nil Timeout.timeout(self.fallback_timeout) do parsed_response = JSON.parse RestClient::Request.execute(:method => :get, :url => lookup_url(ip, ), :timeout => self.timeout) location = to_j(parsed_response, ) 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, = {}) set_defaults_if_necessary 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 args = [:country, :province,:city] if [:precision] && !args.include?([:precision]) raise 'Invalid precision.' end end |
.timeout ⇒ Object
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 |