File: ipregistry.rb

package info (click to toggle)
ruby-geocoder 1.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 900 kB
  • sloc: ruby: 8,419; makefile: 3
file content (68 lines) | stat: -rw-r--r-- 1,491 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'geocoder/lookups/base'
require 'geocoder/results/ipregistry'

module Geocoder::Lookup
  class Ipregistry < Base

    ERROR_CODES = {
      400 => Geocoder::InvalidRequest,
      401 => Geocoder::InvalidRequest,
      402 => Geocoder::OverQueryLimitError,
      403 => Geocoder::InvalidApiKey,
      451 => Geocoder::RequestDenied,
      500 => Geocoder::Error
    }
    ERROR_CODES.default = Geocoder::Error

    def name
      "Ipregistry"
    end

    def supported_protocols
      [:https, :http]
    end

    private

    def base_query_url(query)
      "#{protocol}://#{host}/#{query.sanitized_text}?"
    end

    def cache_key(query)
      query_url(query)
    end

    def host
      configuration[:host] || "api.ipregistry.co"
    end

    def query_url_params(query)
      {
        key: configuration.api_key
      }.merge(super)
    end

    def results(query)
      # don't look up a loopback or private address, just return the stored result
      return [reserved_result(query.text)] if query.internal_ip_address?

      return [] unless (doc = fetch_data(query))

      if (error = doc['error'])
        code = error['code']
        msg = error['message']
        raise_error(ERROR_CODES[code], msg ) || Geocoder.log(:warn, "Ipregistry API error: #{msg}")
        return []
      end
      [doc]
    end

    def reserved_result(ip)
      {
        "ip"           => ip,
        "country_name" => "Reserved",
        "country_code" => "RD"
      }
    end
  end
end