worldwide 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a0c997e23c5f4ee1ae1b12a1fbca3a9a6fb7c807d1d846b187661863835d5a3b
4
- data.tar.gz: 59a34f1f08733f73dfe1f20d1a1ee6b3b272ddfb968def8ef881737897b9cf37
3
+ metadata.gz: 6ec161f3acc3ffbbf0d5567f4515869a161edc7178a5ae9fc06da9471b0702b5
4
+ data.tar.gz: 50aeec95bb6ee2dadac443d0a161d3f1de6154b01a8f855e6465d273f6c1c33c
5
5
  SHA512:
6
- metadata.gz: 557a21b9c39b758ad37e4e1cd36a8bbf69bb63118b591a4a652d8bb21406dff28524d63017e75f0e7f925898e68a2ff03e43db41411299cd822795b6e8d9e1c1
7
- data.tar.gz: 16c5eddd8ef7ba8df4edcc4f8355ecfce2a09007a3de6645297219c038b9f518a4ee7fdb40db190fa8817128be17a2184157ebf23640235d335fcb496c3a8fa9
6
+ metadata.gz: 662c293b9dcd41e95c2e5eb91afbfeef24a2312a80e689a63049b1e8fddccca626315a81e29340fee831ccf40dcb10bebfdf087cee23f25b77a745b4a212c6bc
7
+ data.tar.gz: 25e7d1faed5b58b2a7b23b05f8208e96f73f619fbf020ccff1c27e7f6daba157c9ef0ef60dcbda72259a2bbfd8ea87cdbe32dd5c5a1214a8bc1cbad084423dcf
@@ -20,11 +20,12 @@ The most important guidelines:
20
20
 
21
21
  - All changes should be covered by tests.
22
22
  - Your code should support all the Ruby versions we have enabled on CI.
23
- - Do not update the CHANGELOG, or the `Worldwide::VERSION` constant.
23
+ - Add an entry under `Unreleased` in [`CHANGELOG.md`](../CHANGELOG.md) for every change except routine updates such as dependency bumps. Add the public PR link once it exists.
24
+ - Leave `Worldwide::VERSION` unchanged unless this PR also prepares a release.
24
25
 
25
26
  ### Releasing
26
27
 
27
28
  1. Check the [semantic versioning page](http://semver.org) for info on how to version the new release.
28
29
  2. Update the `Worldwide::VERSION` constant in **lib/worldwide/version.rb**.
29
- 3. Add a `CHANGELOG.md` entry for the new release with the date.
30
+ 3. Move the entries for this release from `Unreleased` to a dated section in `CHANGELOG.md`.
30
31
  4. Release the gem to rubygems using ShipIt (this will create tag/push during deploy)
@@ -17,11 +17,11 @@ jobs:
17
17
  - name: Check out code
18
18
  uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19
19
  - name: Setup Node
20
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
20
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
21
21
  with:
22
22
  node-version: 20
23
23
  - name: Setup PNPM
24
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
24
+ uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
25
25
  with:
26
26
  version: 9.1.3
27
27
  - name: Install dependencies
@@ -8,7 +8,9 @@ on:
8
8
 
9
9
  jobs:
10
10
  build:
11
- runs-on: ubuntu-latest
11
+ # ubuntu-latest moved to 26.04, whose tzdata no longer resolves America/Godthab (data/regions/GL.yml).
12
+ # Remove this pin once GL.yml uses America/Nuuk.
13
+ runs-on: ubuntu-24.04
12
14
  name: Ruby ${{ matrix.ruby }} / ${{ matrix.gemfile }}
13
15
  strategy:
14
16
  fail-fast: false
@@ -22,7 +24,7 @@ jobs:
22
24
  - name: Check out code
23
25
  uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
24
26
  - name: Set up Ruby ${{ matrix.ruby }}
25
- uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0
27
+ uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0
26
28
  with:
27
29
  ruby-version: ${{ matrix.ruby }}
28
30
  bundler-cache: true
@@ -24,11 +24,11 @@ jobs:
24
24
  with:
25
25
  token: ${{ secrets.SHOPIFY_GH_ACCESS_TOKEN }}
26
26
  - name: Setup Node
27
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
27
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
28
28
  with:
29
29
  node-version: 24
30
30
  - name: Setup PNPM
31
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
31
+ uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
32
32
  with:
33
33
  version: 9.1.3
34
34
  - name: Install dependencies
data/.gitignore CHANGED
@@ -29,3 +29,6 @@ Thumbs.db
29
29
  # Vendored CLDR data downloaded during `rake cldr:data:import`
30
30
  # Contains temporary Unicode CLDR files used to generate data/cldr/
31
31
  /vendor/
32
+
33
+ # Files downloaded by the `postal:codes:import` rake task
34
+ /rake/postal/vendor/
data/AGENTS.md ADDED
@@ -0,0 +1,57 @@
1
+ # Contributing to Worldwide
2
+
3
+ Worldwide is a public Ruby gem for localization and address handling. It also contains the public `@shopify/worldwide` TypeScript package.
4
+
5
+ ## Keep contributions public
6
+
7
+ - Use public sources and synthetic address examples. Use a published address for a public institution only when the example needs a real location.
8
+ - Do not include customer or merchant data, internal links, private tickets, logs, screenshots, credentials, or unpublished findings. This rule also applies to PR text, comments, commit messages, fixtures, generated data, and CI output.
9
+ - Cite the public source for data changes. Prefer the relevant postal authority, government agency, ISO list, Unicode CLDR, or IANA time zone database. Check that readers can open the source without private access. Check the license and keep any required attribution.
10
+
11
+ ## Find the right file
12
+
13
+ | Change | Start here |
14
+ | --- | --- |
15
+ | Address layouts, postal rules, zone codes, country settings | `data/regions/<CC>.yml`, `lib/worldwide/region.rb`, `lib/worldwide/zip.rb` |
16
+ | Region labels and translations | `data/regions/<CC>/`, `data/cldr/`, `data/other/` |
17
+ | CLDR corrections | [`rake/cldr/patch.rb`](rake/cldr/patch.rb), [`rake/tasks/cldr.rake`](rake/tasks/cldr.rake) |
18
+ | Postal prefix imports | [`rake/postal/README.md`](rake/postal/README.md) |
19
+ | TypeScript address code | [`lang/typescript/`](lang/typescript/) |
20
+
21
+ ## Make the change easy to review
22
+
23
+ - Keep the change to one behavior or one related group of countries. Split unrelated cleanup and dependency updates into separate PRs.
24
+ - Match nearby YAML key order, indentation, and quoting. For generated CLDR data, change the patch or generator and include the matching output. Run `bundle exec rake cldr:data:generate_paths` after you add, move, or remove indexed data files.
25
+ - Treat changes to canonical codes, defaults, locale scripts, fallback rules, and validation as API changes. Show the old and new output. Keep historical codes as lookup alternates when appropriate. Test lookup by both codes and check the value the API returns.
26
+ - For postal changes, test old and new formats, normalization, and invalid input. Check that examples match the rule. An example can also affect the reported postal code type. For address layouts, check both `edit` and `show` where applicable. See [Address format strings](docs/address_format_strings.md).
27
+ - Add focused Minitest coverage next to related tests. For country-specific tests in `test/worldwide/regions/`, use `<cc>_test.rb` and a class such as `PaTest`. If shared region data changes, check its effect on the TypeScript package too.
28
+
29
+ ## Run checks
30
+
31
+ Use `.ruby-version` for local setup. Check [`worldwide.gemspec`](worldwide.gemspec) for the supported Ruby minimum and [Ruby CI](.github/workflows/ci.yml) for the test matrix. Do not assume the oldest Ruby in CI is the supported minimum.
32
+
33
+ ```sh
34
+ bundle install
35
+ bundle exec ruby -Itest test/worldwide/regions/pa_test.rb # example focused test
36
+ bin/test
37
+ bin/style
38
+ ```
39
+
40
+ Run `bin/test-cldr-rake-tasks` from a clean checkout to check that the full CLDR pipeline reproduces the committed data. The script downloads data and reports unexpected changes to the working tree.
41
+
42
+ For changes that affect TypeScript, use the Node and pnpm versions in [TypeScript CI](.github/workflows/ci-typescript.yml):
43
+
44
+ ```sh
45
+ cd lang/typescript
46
+ pnpm install
47
+ pnpm typecheck
48
+ pnpm lint
49
+ pnpm test
50
+ pnpm build
51
+ ```
52
+
53
+ ## Open the PR
54
+
55
+ - Use the [PR template](.github/pull_request_template.md). State the problem, why you chose this fix, which behavior changes, and what you tested. Include public sources, a small reproduction, or a before-and-after example when useful.
56
+ - Add an entry under `Unreleased` in [`CHANGELOG.md`](CHANGELOG.md) for every change except routine updates such as dependency bumps. Add the public PR link once it exists. Leave the version bump to the release unless a maintainer asks for both in the same PR.
57
+ - For a TypeScript change that affects package users, add a changeset with `pnpm changeset` from `lang/typescript`. See the [package README](lang/typescript/README.md) for the release process.
data/CHANGELOG.md CHANGED
@@ -29,6 +29,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
29
29
 
30
30
  ---
31
31
 
32
+ ## [2.4.0] - 2026-11-18
33
+
34
+ - Add `Region#has_code?`, `Region#has_name?`, `Region#has_handle?`, `Region#neighbor?` and `Region#valid_zone_zip?`, for matching a zone by code, by name and by zip, and `Util.utf8_handle` and `Util.ascii_casecmp_substring?`, which they use. `valid_zone_zip?` checks a province's own `zip_prefixes`. `valid_zip?` is unchanged: it infers one province from the zip, so it can differ for a shared prefix or a zip shorter than a prefix. [#682](https://github.com/Shopify/worldwide/pull/682)
35
+ - `Zip.normalize` no longer drops letters from a complete GB-style postcode that has extra characters after it, for example `"E1 6AN 1AA"`. `Zip.outcode` no longer raises `NoMethodError` for such input in GG, IM and JE. [#683](https://github.com/Shopify/worldwide/pull/683)
36
+ - `Zip.find_country` gives no suggestion for a postal code that has no uppercase letters when no country matches the alleged country, and treats a blank country code like `nil` instead of raising `ArgumentError`. [#683](https://github.com/Shopify/worldwide/pull/683)
37
+ - Add tests and fixtures that check which postal codes are valid for each country. [#683](https://github.com/Shopify/worldwide/pull/683)
38
+
39
+ ---
40
+
41
+ ## [2.3.0] - 2026-11-18
42
+
43
+ - Add an `AGENTS.md` contribution guide and document when contributors need a changelog entry. [#686](https://github.com/Shopify/worldwide/pull/686)
44
+ - Add the `postal:codes:import`, `postal:codes:check` and `postal:codes:zone_check` rake tasks. They build and check the `zip_prefixes` and `zips_crossing_provinces` data in `data/regions/<CC>.yml`. [#680](https://github.com/Shopify/worldwide/pull/680)
45
+ - Correct Gabon's default currency from XOF to XAF, as listed in [ISO 4217](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml). XOF remains supported. [#684](https://github.com/Shopify/worldwide/pull/684)
46
+
47
+ ---
48
+
32
49
  ## [2.2.0] - 2026-11-12
33
50
 
34
51
  - The Italian province of Sulcis Iglesiente now uses its current official code `SU`. `CI` stays as a code alternate, so lookups by `CI` still resolve, but `zone.code` now returns `SU`. Its ISO code stays `IT-CI` to keep CLDR's Sulcis Iglesiente names (CLDR's `itsu` is the former Sud Sardegna). [#667](https://github.com/Shopify/worldwide/pull/667)
data/Gemfile CHANGED
@@ -26,6 +26,12 @@ group :development do
26
26
  gem "pry-byebug", "< 3.12", require: false
27
27
  end
28
28
 
29
+ # Used by the postal code rake tasks in rake/postal. The gemspec does not package rake/, so the gem does not depend on them.
30
+ group :development, :test do
31
+ gem "csv"
32
+ gem "rubyzip"
33
+ end
34
+
29
35
  group :test do
30
36
  gem "minitest", "~> 5.27"
31
37
  gem "minitest-reporters"
data/Gemfile.lock CHANGED
@@ -13,7 +13,7 @@ GIT
13
13
  PATH
14
14
  remote: .
15
15
  specs:
16
- worldwide (2.2.0)
16
+ worldwide (2.4.0)
17
17
  activesupport (>= 7.0)
18
18
  i18n (>= 1.15)
19
19
  phonelib (~> 0.8)
@@ -43,6 +43,7 @@ GEM
43
43
  coderay (1.1.3)
44
44
  concurrent-ruby (1.3.8)
45
45
  connection_pool (2.5.5)
46
+ csv (3.3.7)
46
47
  drb (2.2.3)
47
48
  i18n (1.15.2)
48
49
  concurrent-ruby (~> 1.0)
@@ -141,6 +142,7 @@ PLATFORMS
141
142
  x86_64-linux
142
143
 
143
144
  DEPENDENCIES
145
+ csv
144
146
  minitest (~> 5.27)
145
147
  minitest-focus
146
148
  minitest-reporters
@@ -155,6 +157,7 @@ DEPENDENCIES
155
157
  rubocop-shopify
156
158
  ruby-cldr!
157
159
  ruby-lsp
160
+ rubyzip
158
161
  worldwide!
159
162
 
160
163
  BUNDLED WITH
data/data/regions/GA.yml CHANGED
@@ -3,7 +3,7 @@ name: Gabon
3
3
  code: GA
4
4
  tax: 0.18
5
5
  tax_name: VAT
6
- currency: XOF
6
+ currency: XAF
7
7
  group: African Countries
8
8
  group_name: Africa
9
9
  unit_system: metric
@@ -17,6 +17,12 @@ module Worldwide
17
17
  ).to_set.freeze
18
18
  private_constant :ISO_3166_ASSIGNED_COUNTRY_CODES
19
19
 
20
+ CODE_SEPARATOR = "-"
21
+ private_constant :CODE_SEPARATOR
22
+
23
+ BLANK_CODE = /\A[[:space:]]*\z/
24
+ private_constant :BLANK_CODE
25
+
20
26
  # Accpetable format types of the postal code.
21
27
  FORMAT_TYPES = {
22
28
  ALPHANUMERIC: "ALPHANUMERIC",
@@ -164,10 +170,10 @@ module Worldwide
164
170
 
165
171
  # Other names that may be used to refer to this region.
166
172
  # E.g., "Czech Republic" is also known as "Czechia".
167
- attr_accessor :name_alternates
173
+ attr_reader :name_alternates
168
174
 
169
- # iso_code values of regions (subdivisions) within the same country that border this region.
170
- # E.g., for CA-ON, the neighbouring zones are CA-MB, CA-NU and CA-QC.
175
+ # legacy_code values of regions (subdivisions) within the same country that border this region.
176
+ # E.g., for CA-ON, the neighbouring zones are "QC" and "MB".
171
177
  attr_accessor :neighbours
172
178
 
173
179
  alias_method :neighbors, :neighbours
@@ -336,6 +342,12 @@ module Worldwide
336
342
  @zones_by_code = {}
337
343
  end
338
344
 
345
+ def name_alternates=(names)
346
+ @name_alternates = names
347
+ @handle = nil
348
+ @handle_alternates = nil
349
+ end
350
+
339
351
  def inspect
340
352
  "#<#{self.class.name}:#{object_id} #{inspected_fields}>"
341
353
  end
@@ -557,6 +569,114 @@ module Worldwide
557
569
  valid_normalized_zip?(normalized, partial_match: partial_match)
558
570
  end
559
571
 
572
+ # Is the given postal code value valid for this region, judging a province by its own zip prefixes?
573
+ #
574
+ # For a region that is not a province, this gives the same result as {#valid_zip?}.
575
+ #
576
+ # For a province, {#valid_zip?} infers one province from the zip, and accepts the zip only when that is
577
+ # this province or when `zips_crossing_provinces` lists it. This method instead accepts the zip when
578
+ # the country accepts it and one of this province's own `zip_prefixes` matches it. The two differ when:
579
+ #
580
+ # - the province has no `zip_prefixes`, but other provinces of its country do: this method accepts
581
+ # any zip that the country accepts, and {#valid_zip?} accepts only a zip that infers this province;
582
+ # - the prefixes of two provinces both match the zip, for example a partial zip such as "CH6" or a
583
+ # shared prefix such as "K1A": this method accepts the zip for each of them, and {#valid_zip?}
584
+ # accepts it for the first one that it finds, and for the others only through `zips_crossing_provinces`.
585
+ #
586
+ # @example
587
+ # Worldwide.region(code: "CA-ON").valid_zone_zip?("K2A") == false
588
+ # Worldwide.region(code: "CA-ON").valid_zone_zip?("K2A", partial_match: true) == true
589
+ #
590
+ # @param zip [String]
591
+ # @param partial_match [Boolean] also accept the first part of a zip, as `valid_zip?` does
592
+ # @return [Boolean]
593
+ def valid_zone_zip?(zip, partial_match: false)
594
+ return valid_zip?(zip, partial_match: partial_match) unless province?
595
+
596
+ country = associated_country
597
+ return false if country.nil? || country.iso_code.nil?
598
+
599
+ country_code = country.iso_code
600
+ normalized = Zip.normalize(country_code: country_code, zip: zip)
601
+ adjusted = Zip.strip_optional_country_prefix(country_code: country_code, zip: normalized)
602
+
603
+ return false unless country.send(:valid_normalized_zip?, adjusted, partial_match: partial_match)
604
+ return true if Util.blank?(zip) && !country.zip_required?
605
+ return true if Util.blank?(zip_prefixes)
606
+ return true if country.send(:cross_border_zip_includes_province?, zip: adjusted, province_code: legacy_code)
607
+
608
+ zip_prefixes.any? { |prefix| adjusted.start_with?(prefix) || prefix.start_with?(adjusted) }
609
+ end
610
+
611
+ # Does the given code identify this region?
612
+ #
613
+ # The code may be the region's `legacy_code`, one of its `code_alternates`, or its `iso_code`.
614
+ # For a region within a country, the code may also carry the country's code in place of
615
+ # the hyphen-less part: "CA-NL" matches the region with legacy code "NL" in Canada.
616
+ # And, for a region whose legacy code has a hyphen, the part after the hyphen alone is enough:
617
+ # "13" matches the region with legacy code "JP-13".
618
+ #
619
+ # The comparison ignores the case of ASCII letters.
620
+ # Callers may look a region up by code very often, so this allocates no strings.
621
+ #
622
+ # @example
623
+ # Worldwide.region(code: "CA-QC").has_code?("PQ") == true
624
+ # Worldwide.region(code: "CA-QC").has_code?("ca-qc") == true
625
+ # Worldwide.region(code: "JP-13").has_code?("13") == true
626
+ #
627
+ # @param code [String, Symbol]
628
+ # @return [Boolean]
629
+ def has_code?(code)
630
+ return false if code.nil?
631
+
632
+ code = code.to_s unless code.is_a?(String)
633
+ return false if code.empty? || BLANK_CODE.match?(code)
634
+
635
+ return true if legacy_code&.casecmp(code)&.zero?
636
+ return true if code_alternates&.any? { |code_alternate| code_alternate.casecmp(code)&.zero? }
637
+ return true if iso_code&.casecmp(code)&.zero?
638
+
639
+ match_unprefixed_code?(code) || match_suffix_only_code?(code)
640
+ end
641
+
642
+ # Does the given name identify this region?
643
+ #
644
+ # The name is compared with the region's `legacy_name` and its `name_alternates`, after
645
+ # {Util.utf8_handle} simplifies each of them, so that "Fayyum" matches "Fayyūm".
646
+ # It is not compared with the localized {#full_name}.
647
+ #
648
+ # @param name [String]
649
+ # @return [Boolean]
650
+ def has_name?(name)
651
+ has_handle?(name.nil? ? nil : Util.utf8_handle(name))
652
+ end
653
+
654
+ # Does the given handle identify this region?
655
+ #
656
+ # A handle is the result of {Util.utf8_handle}. It is compared with the handle of the region's
657
+ # `legacy_name` and with the handles of its `name_alternates`.
658
+ #
659
+ # @param handle [String]
660
+ # @return [Boolean]
661
+ def has_handle?(handle)
662
+ return false if handle.nil?
663
+
664
+ handle == name_handle || name_alternate_handles.include?(handle)
665
+ end
666
+
667
+ # Is the region with the given legacy code one of the regions that border this region?
668
+ #
669
+ # @example
670
+ # Worldwide.region(code: "CA-ON").neighbor?("QC") == true
671
+ #
672
+ # @param code [String] a legacy code, as found in {#neighbours}
673
+ # @return [Boolean]
674
+ def neighbor?(code)
675
+ return false if neighbours.nil?
676
+
677
+ neighbours.include?(code)
678
+ end
679
+
560
680
  # are zones optional for this region?
561
681
  def province_optional?
562
682
  province_optional || !@zones&.any?(&:province?)
@@ -571,6 +691,77 @@ module Worldwide
571
691
 
572
692
  private
573
693
 
694
+ def name_handle
695
+ return if legacy_name.nil?
696
+
697
+ @handle ||= Util.utf8_handle(legacy_name)
698
+ end
699
+
700
+ def name_alternate_handles
701
+ @handle_alternates ||= (name_alternates || []).map { |name| Util.utf8_handle(name) }.freeze
702
+ end
703
+
704
+ # Matches a code that has this region's country code, a hyphen, and then this region's legacy code
705
+ # or one of its code alternates. E.g., "CA-NL", to match just the "NL" part.
706
+ #
707
+ # This avoids String#split, so that it allocates no strings.
708
+ def match_unprefixed_code?(code)
709
+ return false unless province?
710
+
711
+ hyphen_index = code.byteindex(CODE_SEPARATOR)
712
+ return false unless hyphen_index && hyphen_index != 0 && hyphen_index + 1 < code.bytesize
713
+
714
+ country_code = parent_country&.iso_code
715
+ return false if country_code.nil? || country_code.empty?
716
+
717
+ return false unless Util.ascii_casecmp_substring?(
718
+ country_code,
719
+ code,
720
+ start1: 0,
721
+ length1: country_code.bytesize,
722
+ start2: 0,
723
+ length2: hyphen_index,
724
+ )
725
+
726
+ suffix_start = hyphen_index + 1
727
+ suffix_length = code.bytesize - suffix_start
728
+
729
+ return true if suffix_matches?(legacy_code, code, suffix_start, suffix_length)
730
+
731
+ !!code_alternates&.any? { |code_alternate| suffix_matches?(code_alternate, code, suffix_start, suffix_length) }
732
+ end
733
+
734
+ def suffix_matches?(candidate, code, suffix_start, suffix_length)
735
+ return false if candidate.nil? || candidate.empty?
736
+
737
+ Util.ascii_casecmp_substring?(
738
+ candidate,
739
+ code,
740
+ start1: 0,
741
+ length1: candidate.bytesize,
742
+ start2: suffix_start,
743
+ length2: suffix_length,
744
+ )
745
+ end
746
+
747
+ # Matches a code that is only the part of this region's legacy code after the hyphen,
748
+ # e.g., "13" for "JP-13". Code alternates do not take part, to avoid matching by accident.
749
+ def match_suffix_only_code?(code)
750
+ return false if legacy_code.nil?
751
+
752
+ hyphen_index = legacy_code.byteindex(CODE_SEPARATOR)
753
+ return false if hyphen_index.nil? || hyphen_index == legacy_code.bytesize - 1
754
+
755
+ Util.ascii_casecmp_substring?(
756
+ legacy_code,
757
+ code,
758
+ start1: hyphen_index + 1,
759
+ length1: legacy_code.bytesize - hyphen_index - 1,
760
+ start2: 0,
761
+ length2: code.bytesize,
762
+ )
763
+ end
764
+
574
765
  def add_zone_to_hash(zone)
575
766
  @zones_by_code[subdivision_code(zone.iso_code)] = zone if Util.present?(subdivision_code(zone.iso_code))
576
767
  @zones_by_code[zone.alpha_three] = zone if Util.present?(zone.alpha_three)
@@ -2,6 +2,40 @@
2
2
 
3
3
  module Worldwide
4
4
  class Util
5
+ # Characters in U+00C0..U+017F that have no decomposition into a base letter and a mark,
6
+ # mapped to an ASCII approximation.
7
+ HANDLE_APPROXIMATIONS = {
8
+ "ß" => "ss",
9
+ "æ" => "ae",
10
+ "ð" => "d",
11
+ "ø" => "o",
12
+ "þ" => "th",
13
+ "đ" => "d",
14
+ "ħ" => "h",
15
+ "ı" => "i",
16
+ "ij" => "ij",
17
+ "ĸ" => "k",
18
+ "ŀ" => "l",
19
+ "ł" => "l",
20
+ "ʼn" => "'n",
21
+ "ŋ" => "ng",
22
+ "œ" => "oe",
23
+ "ŧ" => "t",
24
+ }.freeze
25
+ private_constant :HANDLE_APPROXIMATIONS
26
+
27
+ HANDLE_LATIN_RANGE = /[\u00C0-\u017F]/
28
+ private_constant :HANDLE_LATIN_RANGE
29
+
30
+ HANDLE_QUOTES_AND_BRACKETS = "'\"()[]"
31
+ private_constant :HANDLE_QUOTES_AND_BRACKETS
32
+
33
+ HANDLE_SEPARATOR = /(?:(?!\p{Word}|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier}).)+/m
34
+ private_constant :HANDLE_SEPARATOR
35
+
36
+ HANDLE_EDGE_HYPHENS = /\A-+|-+\z/
37
+ private_constant :HANDLE_EDGE_HYPHENS
38
+
5
39
  class << self
6
40
  def blank?(value)
7
41
  value.nil? ||
@@ -12,6 +46,73 @@ module Worldwide
12
46
  def present?(value)
13
47
  !blank?(value)
14
48
  end
49
+
50
+ # Reduces a name to a simplified, lowercase form that is suitable for comparing names.
51
+ # Latin letters with diacritics become their base letters, quotes and brackets are dropped, and each
52
+ # run of other punctuation or whitespace becomes a single hyphen.
53
+ # Letters of other scripts are kept.
54
+ #
55
+ # @example
56
+ # Worldwide::Util.utf8_handle("Al Fayyūm") == "al-fayyum"
57
+ # Worldwide::Util.utf8_handle("Ærøskøbing 日本") == "aeroskobing-日本"
58
+ #
59
+ # @param input [String]
60
+ # @return [String] a new, frozen string
61
+ def utf8_handle(input)
62
+ string = input.to_s
63
+ string = string.dup.force_encoding(Encoding::UTF_8) unless string.encoding == Encoding::UTF_8
64
+ string = ActiveSupport::Multibyte::Unicode.tidy_bytes(string) unless string.valid_encoding?
65
+
66
+ result = string.downcase.unicode_normalize(:nfc)
67
+ result = result.gsub(HANDLE_LATIN_RANGE) do |char|
68
+ HANDLE_APPROXIMATIONS[char] || char.unicode_normalize(:nfd).delete("\u0300-\u036F")
69
+ end
70
+ result.delete!(HANDLE_QUOTES_AND_BRACKETS)
71
+ result.gsub!(HANDLE_SEPARATOR, "-")
72
+ result.gsub!(HANDLE_EDGE_HYPHENS, "")
73
+ result.freeze
74
+ end
75
+
76
+ # Compares a part of one string with a part of another string, ignoring the case of ASCII letters.
77
+ # This allocates no objects, because it compares bytes with `getbyte`.
78
+ # A comparison that involves a byte outside of ASCII is always false.
79
+ #
80
+ # @param str1 [String]
81
+ # @param str2 [String]
82
+ # @param start1 [Integer] the byte offset of the part of `str1`
83
+ # @param length1 [Integer] the byte length of the part of `str1`; it must be greater than 0
84
+ # @param start2 [Integer] the byte offset of the part of `str2`
85
+ # @param length2 [Integer] the byte length of the part of `str2`; it must be greater than 0
86
+ # @return [Boolean]
87
+ # @raise [ArgumentError] when a string is nil, a length is not positive, or a start is negative
88
+ def ascii_casecmp_substring?(str1, str2, start1:, length1:, start2:, length2:)
89
+ raise ArgumentError, "str1 and str2 must not be nil" if str1.nil? || str2.nil?
90
+ raise ArgumentError, "Length must be greater than 0" if length1 <= 0 || length2 <= 0
91
+ raise ArgumentError, "Start indices must not be negative" if start1 < 0 || start2 < 0
92
+
93
+ return false if length1 != length2
94
+
95
+ length = length1
96
+ return false if start1 + length > str1.bytesize || start2 + length > str2.bytesize
97
+
98
+ # A while loop avoids allocating a Range
99
+ i = 0
100
+ while i < length
101
+ b1 = str1.getbyte(start1 + i)
102
+ b2 = str2.getbyte(start2 + i)
103
+
104
+ return false if b1 >= 128 || b2 >= 128
105
+
106
+ b1 += 32 if b1.between?(65, 90)
107
+ b2 += 32 if b2.between?(65, 90)
108
+
109
+ return false if b1 != b2
110
+
111
+ i += 1
112
+ end
113
+
114
+ true
115
+ end
15
116
  end
16
117
  end
17
118
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Worldwide
4
- VERSION = "2.2.0"
4
+ VERSION = "2.4.0"
5
5
  end
data/lib/worldwide/zip.rb CHANGED
@@ -52,7 +52,7 @@ module Worldwide
52
52
  def find_country(country_code: nil, zip:, min_confidence: 0)
53
53
  return unless Util.present?(zip)
54
54
 
55
- country = Worldwide.region(code: country_code) unless country_code.nil?
55
+ country = Worldwide.region(code: country_code) unless Util.blank?(country_code)
56
56
  return country if country&.valid_zip?(zip)
57
57
 
58
58
  adjusted_zip = zip.strip.upcase
@@ -62,7 +62,8 @@ module Worldwide
62
62
  return suggestion unless suggestion.nil? || confidence.nil? || confidence < min_confidence
63
63
 
64
64
  # If our postal code is wholly numeric, we can't make an intelligent suggestion without an alleged country.
65
- return unless adjusted_zip.match?(/[A-Z]/)
65
+ # This checks the zip as given, not `adjusted_zip`, so that lowercase letters alone do not trigger a guess.
66
+ return unless zip.match?(/[A-Z]/)
66
67
 
67
68
  # Try a broader-ranging match without considering the alleged country
68
69
  # We'll see if we have only a single suggestion and, if so, return it.
@@ -837,7 +838,7 @@ module Worldwide
837
838
  # "CH6 ".
838
839
 
839
840
  # Check for complete postcode (outcode and incode)
840
- m = stripped.match(/^([A-Z]{1,2})(\d{1,2})([A-Z])*\s*(\d)([A-Z][A-Z])$/)
841
+ m = stripped.match(/^([A-Z]{1,2})(\d{1,2})([A-Z]){0,1}(\d)([A-Z][A-Z])$/)
841
842
 
842
843
  if m&.size == 6
843
844
  # outcode