Module: IPLocate

Defined in:
lib/iplocate.rb

Constant Summary collapse

API_ENDPOINT =
"https://www.iplocate.io/api/lookup/"

Class Method Summary collapse

Class Method Details

.lookup(ip_address, api_key = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/iplocate.rb', line 10

def self.lookup(ip_address, api_key = nil)
  # Ensure IP address is valid
  raise "Invalid IP address" if not IPAddress.valid? ip_address

  # Add API key if given
  headers = {}
  if not api_key.nil?
    headers[:"X-API-Key"] = api_key
  end

  # Call the API
  endpoint = "#{API_ENDPOINT}#{ip_address}"
  result = RestClient.get(endpoint, headers)

  # Parse the response
  # Let the parser throw JSON::ParserError on invalid response
  result = JSON.parse(result)

  return result.to_h.with_indifferent_access
end