Created
August 6, 2014 12:27
-
-
Save troelskn/c0b661c331af97cb8e73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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