Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created August 6, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/c0b661c331af97cb8e73 to your computer and use it in GitHub Desktop.
Save troelskn/c0b661c331af97cb8e73 to your computer and use it in GitHub Desktop.
require 'ipaddr'
require 'net/http'
require 'uri'
require 'json'
module GeoIP
def self.configuration
@configuration ||= {}
end
def self.configuration=(hash)
@configuration = hash
end
def self.ip_to_country_iso(ip_address)
IPAddr.new(ip_address) # Validation
uri = URI.parse("https://geoip.maxmind.com/geoip/v2.0/country/#{ip_address}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth(configuration[:user_id], configuration[:license_key])
response = http.request(request)
raise "HTTP Error #{response.code} talking to maxmind" unless response.code.to_i == 200
struct = JSON.parse(response.body.to_s)
struct["country"]["iso_code"] if struct["country"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment