Class: PostalCodeLookup
- Inherits:
-
Object
show all
- Includes:
- HTTParty
- Defined in:
- lib/postal_code_lookup.rb
Defined Under Namespace
Classes: ServiceException
Instance Method Summary
collapse
Instance Method Details
#call(env) ⇒ Object
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# File 'lib/postal_code_lookup.rb', line 15
def call(env)
request = Rack::Request.new(env)
= { "Content-Type" => "application/json" }
begin
response = Rack::Response.new(find(request.params['code']), 200, )
response = maybe_cache_response(response)
rescue Exception => e
response = Rack::Response.new({ :error => e.message }.to_json, 500, )
end
response.to_a
end
|
#find(code) ⇒ Object
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/postal_code_lookup.rb', line 29
def find(code)
result = PostalCodeLookup.get('/cgi-bin/postalcode/postalcode.cgi', { :query => { :code => code } })
if error = result["ServiceExceptionReport"]
raise ServiceException.new(error['ServiceException'])
else
postal_code = result['PostalCodeLookup']['PostalCodeResultSet']['PostalCode']
location = postal_code["gml:centerOf"]["gml:Point"]
epsg = location["srsName"].split('#').pop
lng, lat = location["gml:coordinates"].split(',')
return {
:postal_code => postal_code["gml:name"],
:epsg => epsg.to_i,
:srs_name => location["srsName"],
:latitude => lat.to_f,
:longitude => lng.to_f,
:placename => postal_code["Placename"],
:province_or_territory => postal_code["ProvinceOrTerritory"]
}.to_json
end
end
|
#maybe_cache_response(response) ⇒ Object
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/postal_code_lookup.rb', line 51
def maybe_cache_response(response)
begin
cached_response = Rack::Cache::Response.new(response.status, response., response.body)
cached_response.max_age = 1.month
cached_response
rescue
response end
end
|