Skip to content

Instantly share code, notes, and snippets.

@wingrunr21
Created January 4, 2013 23:55
Show Gist options
  • Save wingrunr21/4458606 to your computer and use it in GitHub Desktop.
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.
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