Class: Ip2Geo::Methods::ConvertIP

Inherits:
Object
  • Object
show all
Defined in:
lib/ip2geo/methods/convert_ip.rb

Class Method Summary collapse

Class Method Details

.call(options = {}) ⇒ Hash?

Get geo information from an IP address.

Parameters:

  • options (Hash) (defaults to: {})

    The options for the conversion

Options Hash (options):

  • :ip (String)

    The IP address to retrieve geo information for (required)

Returns:

  • (Hash, nil)

    The API response containing geo data, or nil if the request fails



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
# File 'lib/ip2geo/methods/convert_ip.rb', line 12

def call(options = {})
  ip = options[:ip]

  unless ip
    return error_response(
      Data.translate('conversions.ip-address-is-required-to-convert-it')
    )
  end

  validation = Helpers::IpValidation.validate(ip)

  unless validation[:ip4] || validation[:ip6]
    return error_response(
      Data.translate('conversions.invalid-ip-address-so-we-could-not-convert-it')
    )
  end

  url = "#{Data::API_ENDPOINT}#{Data::ENDPOINTS[:CONVERT]}?ip=#{ip}"

  if Data::State.cache
    cache_key = "convert:#{ip}"
    cached = Helpers::Cache.get(cache_key)

    if cached
      Thread.new do
        fresh = Helpers::Http.request(url)
        Helpers::Cache.set(cache_key, fresh) if fresh && fresh['success']
      rescue StandardError
        # silently ignore background refresh errors
      end

      return cached
    end

    response = Helpers::Http.request(url)
    Helpers::Cache.set(cache_key, response) if response && response['success']
    return response
  end

  Helpers::Http.request(url)
rescue StandardError => e
  warn "[Ip2Geo::ConvertIP] Error: #{e.message}"
  nil
end