diff --git a/lib/geo_code.rb b/lib/geo_code.rb index ab41e9f9f954545c574aad066ad3d1f984504c2a..f223779ef5a20439e8b757e6a69a3176b5af9824 100644 --- a/lib/geo_code.rb +++ b/lib/geo_code.rb @@ -25,4 +25,25 @@ class GeoCode def valid? @data["longt"] && @data["latt"] end + + # geocoder.ca is Canadian; for US coordinates the top-level "prov"/"city" + # may reflect Canadian conventions, so prefer the "usa" sub-object when present + + # @return [String, nil] + def city + if @data["usa"] + @data["usa"]["uscity"] + else + @data["city"] + end + end + + # @return [String, nil] + def state + if @data["usa"] + @data["usa"]["state"] + else + @data["prov"] + end + end end diff --git a/test/test_geo_code.rb b/test/test_geo_code.rb new file mode 100644 index 0000000000000000000000000000000000000000..6e57d859c1889e564bad21a548d781781fda3b02 --- /dev/null +++ b/test/test_geo_code.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require "test_helper" +require "geo_code" + +class GeoCodeTest < Minitest::Test + def test_city_from_top_level + geo = GeoCode.for("city" => "Toronto", "prov" => "ON", "latt" => "43.7", "longt" => "-79.4") + assert_equal "Toronto", geo.city + end + + def test_state_from_top_level + geo = GeoCode.for("city" => "Toronto", "prov" => "ON", "latt" => "43.7", "longt" => "-79.4") + assert_equal "ON", geo.state + end + + def test_city_prefers_usa_object + geo = GeoCode.for( + "city" => "New York", + "prov" => "NY", + "latt" => "40.7", + "longt" => "-74.0", + "usa" => { "uscity" => "Manhattan", "state" => "NY" } + ) + assert_equal "Manhattan", geo.city + end + + def test_state_prefers_usa_object + geo = GeoCode.for( + "city" => "New York", + "prov" => "NY", + "latt" => "40.7", + "longt" => "-74.0", + "usa" => { "uscity" => "Manhattan", "state" => "NY" } + ) + assert_equal "NY", geo.state + end +end