Skip to content

Commit

Permalink
allow zone lookup by partial zip if country hides provinces
Browse files Browse the repository at this point in the history
  • Loading branch information
rochlefebvre committed Feb 24, 2025
1 parent e9cc59b commit 9020c42
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
19 changes: 11 additions & 8 deletions lib/worldwide/region.rb
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,10 @@ def zone(code: nil, name: nil, zip: nil)
search_name == I18n.with_locale(:en) { region.full_name&.upcase }
end
else # Worldwide::Util.present?(zip)
zone_by_normalized_zip(Zip.normalize(country_code: iso_code, zip: zip))
zone_by_normalized_zip(
Zip.normalize(country_code: iso_code, zip: zip),
allow_partial_zip: hide_provinces_from_addresses,
)
end || Worldwide.unknown_region
end

Expand Down Expand Up @@ -496,6 +499,13 @@ def province_optional?
province_optional || !@zones&.any?(&:province?)
end

# Returns true if this country has zones defined, and has postal code prefix data for the zones
def has_zip_prefixes?
@zones&.any? do |zone|
Util.present?(zone.zip_prefixes)
end
end

private

def add_zone_to_hash(zone)
Expand Down Expand Up @@ -542,13 +552,6 @@ def cross_border_zip_includes_province?(zip:, province_code:)
false
end

# Returns true if this country has zones defined, and has postal code prefix data for the zones
def has_zip_prefixes?
@zones&.any? do |zone|
Util.present?(zone.zip_prefixes)
end
end

def inspected_fields
INSPECTION_FIELDS.map { |field_name| "@#{field_name}=#{send(field_name).inspect}" }.join(", ")
end
Expand Down
18 changes: 18 additions & 0 deletions test/worldwide/region_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ class RegionTest < ActiveSupport::TestCase
assert_equal "CA-BC", zone.iso_code
end

test "#zone cannot look up a zone by partial zip if country shows provinces" do
zone = Worldwide.region(code: "CA").zone(zip: "V6B") # Canada does not hide provinces

assert_equal Worldwide.unknown_region, zone
end

test "#zone can look up a zone by partial zip if country hides provinces" do
zone = Worldwide.region(code: "GB").zone(zip: "SW1") # UK hides provinces

assert_equal "GB-ENG", zone.iso_code
end

test "#zone can look up zones that go by iso_code" do
[
["MX", "AGU", "MXAGU", "MX-AGU", "Aguascalientes"],
Expand Down Expand Up @@ -557,5 +569,11 @@ class RegionTest < ActiveSupport::TestCase
assert Worldwide.region(code: "NZ").province_optional
refute Worldwide.region(code: "CA").province_optional
end

test "#has_zip_prefixes? returns values as expected" do
refute_predicate Worldwide.region(code: "FR"), :has_zip_prefixes? # no zones
refute_predicate Worldwide.region(code: "AR"), :has_zip_prefixes? # zones but no prefixes
assert_predicate Worldwide.region(code: "US"), :has_zip_prefixes? # zones and prefixes
end
end
end

0 comments on commit 9020c42

Please sign in to comment.