module IPLocate

Constants

API_ENDPOINT

Public Class Methods

lookup(ip_address, api_key = nil) click to toggle source
# 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