@@ -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
@@ -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