Created
January 4, 2013 23:55
-
-
Save wingrunr21/4458606 to your computer and use it in GitHub Desktop.
A quick module for doing postal code lookups from the geonames.org JSON API.
This file contains hidden or 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 'multi_json' | |
module PostalCodeLookup | |
GEONAMES_URL = 'http://api.geonames.org/postalCodeSearchJSON' | |
def self.find_postal_code_data(code) | |
info = nil | |
begin | |
client = HTTPClient.new | |
query = { | |
'postalcode' => code, | |
'maxRows' => 1, | |
'username' => 'demo', | |
'country' => 'US' | |
} | |
res = client.get(GEONAMES_URL, query) | |
if res.status == 200 && res.contenttype =~ /application\/json/ | |
hash = MultiJson.load(res.content) | |
unless hash["postalCodes"].nil? || hash["postalCodes"].empty? | |
info = {} | |
info[:zip] = code | |
info[:state] = hash["postalCodes"].first["adminName1"] | |
info[:short_state] = hash["postalCodes"].first["adminCode1"] | |
info[:city] = hash["postalCodes"].first["placeName"] | |
end | |
end | |
rescue => e | |
Rails.logger.error e.message | |
Rails.logger.error e.backtrace.join("\n") | |
info = nil | |
end | |
return info | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment