### Executing Bundle for Gem Installation Source: https://github.com/shopify/worldwide/blob/main/README.md Runs the `bundle` command to install the gems listed in the `Gemfile`, including `worldwide`. This command resolves and installs all declared dependencies into your project's environment. ```Shell $ bundle ``` -------------------------------- ### Installing Worldwide Gem via Gem Command Source: https://github.com/shopify/worldwide/blob/main/README.md Installs the `worldwide` gem directly from RubyGems.org. This is an alternative to Bundler for global installation or when not managing dependencies via a `Gemfile`. ```Shell $ gem install worldwide ``` -------------------------------- ### Installing Project Dependencies - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Command to install all necessary project dependencies using pnpm, which manages packages for the TypeScript project. ```Shell pnpm install ``` -------------------------------- ### Accessing Sub-Zones and Localized Names (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This example shows how to retrieve a specific sub-zone (province/state) within a country using its code. It demonstrates fetching the full name of the sub-zone and how to get localized names for sub-zones using `I18n.with_locale`. ```Ruby $ ca = Worldwide.region(code: 'CA') => # $ ont = ca.zone(code: 'on') => # $ ont.full_name => "Ontario" $ jp = Worldwide.region(code: 'JP') => # $ okayama = jp.zone(code: 'JP-33') => # $ I18n.with_locale(:en) { okayama.full_name } => "Okayama" $ I18n.with_locale(:ja) { okayama.full_name } => "岡山県" ``` -------------------------------- ### Installing Worldwide Gem in Gemfile Source: https://github.com/shopify/worldwide/blob/main/README.md Adds the `worldwide` gem to your application's `Gemfile`, making it available for use. This is the standard way to declare Ruby gem dependencies for a project. ```Ruby gem 'worldwide' ``` -------------------------------- ### Retrieving Locale Information with Worldwide::Locale (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to use the `Worldwide.locales` and `Worldwide.locale` modules to retrieve various pieces of information about locales. It includes examples for listing all known locales, extracting the language subtag from a locale code, getting a list of valid sub-locales, and identifying the script used by a locale. ```Ruby # Get the list of known locales Worldwide.locales.known # Get the language subtag from a locale Worldwide.locale(code: "pt-BR").language_subtag # Get a list of valid locales (from the CLDR data) Worldwide.locale(code: "it").sub_locales # Which script does the locale use? [:en, :ja, :ru, :'zh-Hans', :'zh-Hant'].map { |locale| [locale, Worldwide.locale(code: locale).script] } ``` -------------------------------- ### Retrieving Currency Name (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to access the human-readable name of a `Worldwide::Currency` object using its `name` attribute. It shows an interactive Ruby (IRB) example of getting the currency's full name. ```Ruby $ currency.name => "US Dollar" ``` -------------------------------- ### Mapping Locale Codes to Names with Worldwide::Locales (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet provides an example of how to generate a hash map where keys are locale codes and values are their translated names. It iterates through all known locales and uses `Worldwide::Locale.new(code).name` to get the name, useful for displaying lists of locales in a UI. ```Ruby map = Worldwide.locales.known.to_h { |code| [ code, Worldwide::Locale.new(code).name ]} ``` -------------------------------- ### Formatting Discount Percentages with Worldwide::Discounts (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates how `Worldwide.discounts` formats discount percentages in a culturally appropriate manner for different locales. It shows examples where a percentage might be displayed as a direct percentage, or as a specific phrase like '8割引' for Japanese or '7.5折' for Chinese. ```Ruby # Format percentage as a discount Worldwide.discounts.format(0.75, locale: :'en-CA') Worldwide.discounts.format(0.1, locale: :'ku') Worldwide.discounts.format(0.8, locale: :'ja') Worldwide.discounts.format(0.85, locale: :'ja') Worldwide.discounts.format(2.5, locale: :'zh-Hans-CN') ``` -------------------------------- ### Formatting Numbers with Worldwide::Numbers (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to use `Worldwide::Numbers` to format numbers according to locale-specific conventions. It shows examples of forcing decimal places, humanizing large numbers (short, long, and Japanese styles), and formatting numbers as percentages, including relative percentages. ```Ruby Worldwide.numbers.format(12345.67) Worldwide.numbers.format(12345.67, decimal_places: 0) Worldwide.numbers(locale: :'fr-FR').format(12345.67) Worldwide.numbers(locale: :en).format(1_500_000) Worldwide.numbers(locale: :en).format(1_500_000, humanize: :long) Worldwide.numbers(locale: :en).format(1_500_000, humanize: :short) Worldwide.numbers(locale: :'fr-Fr').format(2_000_000_000, humanize: :long) Worldwide.numbers(locale: :'ja').format(1_2345, humanize: :japan) Worldwide.numbers(locale: 'en-US').format(0.75, percent: true) Worldwide.numbers(locale: 'fr').format(0.75, percent: true) Worldwide.numbers(locale: 'tr').format(0.75, percent: true) Worldwide.numbers(locale: 'en').format(0.6, percent: true, relative: true) ``` -------------------------------- ### Checking Node and pnpm Versions - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Commands to verify the installed versions of Node.js and pnpm, ensuring they meet the project's requirements (Node v20+ LTS, pnpm v9). ```Shell node -v # ex: v20.13.1, Should be version 20 (or highter LTS) pnpm -v # ex: 9.1.3, Should be version 9 ``` -------------------------------- ### Retrieving Full Month and Weekday Names in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This example shows how to obtain full, translated names for weekdays and months using `Worldwide::Calendar::Gregorian#weekday_names` and `Worldwide::Calendar::Gregorian#month_names`. It specifies the 'en-US' locale to retrieve English names. ```Ruby $ Worldwide::Calendar::Gregorian.weekday_names(locale: :"en-US") => { sun: "Sunday", mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday" } $ Worldwide::Calendar::Gregorian.month_names(locale: :"en-US") => ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ``` -------------------------------- ### Defining Additional Address Fields (YAML) Source: https://github.com/shopify/worldwide/blob/main/README.md This YAML snippet illustrates how country-specific address field definitions and concatenation rules are configured. It shows an example for Brazil (`BR.yml`), detailing which fields are `required` and how they are combined into `address1` and `address2` using `decorator` for formatting. ```YAML # data/region/BR.yml additional_address_fields: - name: streetName required: true - name: streetNumber required: true - name: line2 - name: neighborhood combined_address_format: address1: - key: streetName - key: streetNumber decorator: "," address2: - key: line2 - key: neighborhood decorator: "," ``` -------------------------------- ### Formatting Addresses with Excluded Fields (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This example demonstrates how to customize address formatting by excluding specific fields using the `excluded_fields` option. Here, the `:name` field is omitted from the formatted output, which can be useful for specific display requirements. ```Ruby # You can also hide some fields $ library_address.format( excluded_fields: [:name], ) => [ "British Library", "96 Euston Rd", "London NW1 2DB", "United Kingdom", ] ``` -------------------------------- ### Getting Translated Locale Names with Worldwide::Locale (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet shows how to obtain the translated name of a locale using `Worldwide.locale(code: '...').name`. It demonstrates getting the name in the current locale, specifying a target locale for translation, including region information, and handling unknown or invalid locale codes gracefully. ```Ruby # Get the name translated in the current locale Worldwide.locale(code: 'pt-BR').name # Or you can specify a locale Worldwide.locale(code: "fr-CA").name(locale: :fr) # Add region in parentheses when full locale is provided Worldwide.locale(code: "fr-FR").name Worldwide.locale(code: "bogus-does-not-exist").name(throw: false) || Worldwide::Locale.unknown.name ``` -------------------------------- ### Querying Locale-Specific Time Formatting Rules in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This example shows how `Worldwide::TimeFormatter` can be used to query specific time formatting rules for different locales. It retrieves the hour-minute separator and determines if a 12-hour clock is used for 'en-CA', 'en-DK', and 'fr-CA' locales. ```Ruby $ ['en-CA', 'en-DK', 'fr-CA'].map { |locale| [locale, Worldwide::TimeFormatter.new(locale: locale).hour_minute_separator ] } => [["en-CA", ":"], ["en-DK", "."], ["fr-CA", " h "]] $ ['en-CA', 'en-DK', 'fr-CA'].map { |locale| [locale, Worldwide::TimeFormatter.new(locale: locale).twelve_hour_clock? ] } => [["en-CA", true], ["en-DK", false], ["fr-CA", false]] ``` -------------------------------- ### Retrieving Abbreviated Month and Weekday Names in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to retrieve shorter versions of weekday and month names using the `width` parameter with `Worldwide::Calendar::Gregorian` methods. It shows examples for `:abbreviated` and `:narrow` widths, noting the potential ambiguity of narrow names. ```Ruby $ Worldwide::Calendar::Gregorian.weekday_names(width: :abbreviated) => { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat" } $ Worldwide::Calendar::Gregorian.month_names(width: :abbreviated) => ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # Note that the values returned by `width: :narrow` are not unique # and should only be used in contexts where this ambiguity is not a problem # (e.g., date picker column headings) $ Worldwide::Calendar::Gregorian.weekday_names(width: :narrow) => { sun: "S", mon: "M", tue: "T", wed: "W", thu: "T", fri: "F", sat: "S" } $ Worldwide::Calendar::Gregorian.month_names(width: :narrow) => ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"] ``` -------------------------------- ### Validating Addresses with Worldwide.address (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to validate a `Worldwide::Address` object using the `valid?` method. It shows an example of a valid address and an invalid one, illustrating how to retrieve specific validation errors using the `errors` method, such as an invalid zip code for a given province and country. ```Ruby $ library_address = Worldwide.address( first_name: "Liz", last_name: "Jolly", company: "British Library", address1: "96 Euston Rd", address2: nil, zip: "NW1 2DB", city: "London", country_code: "GB" ) => Worldwide::Address $ library_address.valid? => true $ bogus_address = Worldwide.address( first_name: "John", last_name: "Doe", address1: "123 Fake Street", province_code: "MB", zip: "A1A 1A1", city: "London", country_code: "CA" ) => Worldwide::Address $ bogus_address.valid? => false $ bogus_address.errors => [[:zip, :invalid_for_province_and_country]] # zip in MB must start with R, not A ``` -------------------------------- ### Validating Phone Numbers with Worldwide::Phone (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to validate phone numbers using the `Worldwide::Phone` class. It shows examples of valid numbers, including those with extensions and international formats, and highlights cases where validation might fail due to incorrect country code association or format. ```Ruby $ Worldwide::Phone.new(number: "(613) 555-1212", country_code: "CA").valid? => true $ Worldwide::Phone.new(number: "(613) 555-1212 ext 123", country_code: "CA").valid? => true $ Worldwide::Phone.new(number: "+41 44 268 66 66", country_code: "CA").valid? => true $ Worldwide::Phone.new(number: "44 268 66 66", country_code: "CA").valid? => false ``` -------------------------------- ### Applying Aggressive Address Autocorrection in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This example illustrates how to apply more aggressive address autocorrection using `autocorrect_level: 9` to resolve ambiguous country codes (e.g., 'GE' for Georgia, USA vs. country Georgia). It demonstrates how `normalize!` updates the address in place, making it valid. ```Ruby $ atlanta_address = Worldwide.address( first_name: "Scarlett", last_name: "O'Hara", address1: "181 Peachtree St NE", city: "Atlanta", zip: "30303", country_code: "GE" # Country Georgia, which is not the USA State of Georgia ) => Worldwide::Address $ atlanta_address.country_code => "GE" $ atlanta_address.valid? => false $ atlanta_address.normalize(autocorrect_level: 9).country_code => "US" $ atlanta_address.normalize!(autocorrect_level: 9) => Worldwide::Address $ atlanta_address.province_code => "GA" $ atlanta_address.country_code => "US" $ atlanta_address.valid? => true ``` -------------------------------- ### Integrating Localized Timezones in Rails Forms (ERB) Source: https://github.com/shopify/worldwide/blob/main/README.md This ERB snippet provides an example of how to populate a UI select dropdown with localized timezone options within a Rails form. It utilizes `time_zone_options_for_select` in conjunction with `Worldwide::TimeZone` to offer a user-friendly timezone selection. ```ERB <%= form.ui_select :timezone, time_zone_options_for_select( @shop.timezone.name, nil, Worldwide::TimeZone ), {}, label: t('shop_identity.views.admin.settings.general.timezone_label') %> ``` -------------------------------- ### Initializing Currency Objects for Formatting (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet demonstrates how to initialize `Worldwide::Currency` objects for Euro, Japanese Yen, and US Dollar using their respective ISO codes. These initialized objects are prerequisites for subsequent currency formatting operations. ```Ruby $ eur = Worldwide.currency(code: "EUR") $ jpy = Worldwide.currency(code: "JPY") $ usd = Worldwide.currency(code: "USD") ``` -------------------------------- ### Formatting Currency with Locale (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet demonstrates basic currency formatting using `format_short` and `format_explicit` methods, showing how the output changes based on the specified `locale` (e.g., 'en-US' vs 'fr'). It highlights the difference between short and explicit formats. ```Ruby $ eur = Worldwide.currency(code: "EUR") $ jpy = Worldwide.currency(code: "JPY") $ usd = Worldwide.currency(code: "USD") $ usd.format_short(12.5, locale: "en-US") => "$12.50" $ usd.format_explicit(12.5, locale: "en-US") => "$12.50 USD" $ usd.format_short(12.5, locale: "fr") => "12,50 $" $ usd.format_explicit(12.5, locale: "fr") => "12,50 $ USD" ``` -------------------------------- ### Fetching All Supported Currencies (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet demonstrates how to retrieve a comprehensive list of all supported currency objects using `Worldwide::Currencies.all`. The output shows an array of `Worldwide::Currency` instances. ```Ruby $ currencies = Worldwide::Currencies.all => [#, #, #...] ``` -------------------------------- ### Building the TypeScript Project - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Command to trigger the build process for the TypeScript project. This uses Rollup to bundle the source code into the `dist/` directory, creating the final JS package. ```Shell pnpm build ``` -------------------------------- ### Formatting Addresses with Worldwide.address (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates how to create `Worldwide::Address` objects and format them into multi-line arrays. It demonstrates localized formatting using `I18n.with_locale` for English and Japanese, showing how address components are ordered and displayed differently based on the locale. ```Ruby $ library_address = Worldwide.address( first_name: "Liz", last_name: "Jolly", company: "British Library", address1: "96 Euston Rd", address2: nil, zip: "NW1 2DB", city: "London", country_code: "GB" ) => Worldwide::Address $ library_address.format => [ "Liz Jolly", "British Library", "96 Euston Rd", "London NW1 2DB", "United Kingdom", ] => jr_address = Worldwide.address( first_name: "賢", last_name: "田中", company: "JR東日本", address1: "丸の内1丁目9", zip: "100-0005", city: "千代田区", province_code: "JP-13", country_code: "JP" ) => Worldwide::Address $ I18n.with_locale(:ja) { jr_address.format } => [ "日本 〒100-0005", "東京都 千代田区", "丸の内1丁目9", "JR東日本", "田中 賢様", ] $ I18n.with_locale(:en) { jr_address.format } => [ "Japan 〒100-0005", "Tokyo 千代田区", "丸の内1丁目9", "JR東日本", "田中 賢様", ] ``` -------------------------------- ### Navigating to TypeScript Project Directory - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Command to change the current working directory to the `lang/typescript` folder, which is where all `pnpm` commands for this project should be executed. ```Shell cd lang/typescript ``` -------------------------------- ### Generating Single-Line Address Format (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet shows how to generate a concise, single-line representation of an address using the `single_line` method. It also illustrates how the output adapts to different locales, providing a compact format suitable for identifying locations. ```Ruby $ lon = Worldwide.address( country_code: 'GB', city: 'London' ) => Worldwide::Address $ lon.single_line => "London, United Kingdom" $ I18n.with_locale(:ja) { lon.single_line } => "イギリス:London" $ I18n.with_locale(:'zh-CN') { lon.single_line } => "英国London" ``` -------------------------------- ### Development Utility Commands - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md A collection of common development commands for the project, including running the code linter (eslint), formatting code (prettier), type checking (tsc), running tests (vitest), and running tests in watch mode. ```Shell # Run code linter (w/ eslint) pnpm lint # Run code formatting (w/ prettier) pnpm format # Run typechecker (w/ typescript/tsc) pnpm typecheck # Run test suite (w/ vitest) pnpm test # Run test watcher (w/ vitest) pnpm test:watch ``` -------------------------------- ### Looking Up Zones by Name with Locale (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates looking up a zone within a country by its name, including locale-specific names. It highlights that while possible, it's less reliable than using codes and shows how an unknown region (`ZZ`) is returned if no match is found. ```Ruby $ Worldwide.region(code: "CA").zone(name: "Prince Edward Island")&.iso_code => "CA-PE" $ I18n.with_locale(:fr){ Worldwide.region(code: "CA").zone(name: "Île-du-Prince-Édouard")&.iso_code } => "CA-PE" $ I18n.with_locale(:fr){ Worldwide.region(code: "CA").zone(name: "Québec") } => # $ I18n.with_locale(:fr){Worldwide.region(code: "CA").zone(name: "Province de Québec")} => # # the unknown region, returned when no match is found ``` -------------------------------- ### Defining Show Address Format Grammar (EBNF) Source: https://github.com/shopify/worldwide/blob/main/docs/address_format_strings.md This EBNF grammar defines the syntax for the `show` address format string, used for rendering addresses in a UI. It specifies how lines, fields, and separators are structured, allowing for prefixes and suffixes around fields. Fields are space-separated, and lines are separated by underscores. The `Text` rule defines characters allowed in prefixes/suffixes. ```EBNF ShowFormatString ::= Lines Lines ::= Line (LineSeparator Lines)? LineSeparator ::= '_' Line ::= PrefixedSuffixedField (FieldSeparator PrefixedSuffixedField)* FieldSeparator ::= ' ' PrefixedSuffixedField ::= (Prefix? Field Suffix?) Field ::= '{' Identifier '}' Identifier ::= [a-zA-Z0-9_]+ Prefix ::= Text Suffix ::= Text Text ::= [^_{} ]+ ``` -------------------------------- ### Formatting Currency in Minor Units (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet demonstrates formatting currency amounts in minor units (e.g., cents) using the `as_minor_units: true` option. It also shows how `decimal_places` can be used to control precision even when formatting in minor units, and how `format_explicit` behaves. ```Ruby $ eur = Worldwide.currency(code: "EUR") $ jpy = Worldwide.currency(code: "JPY") $ usd = Worldwide.currency(code: "USD") $ usd.format_short(0.75, as_minor_units: true) ==> "75¢" $ usd.format_short(1.219, as_minor_units: true) ==> "122¢" $ usd.format_short(1.219, as_minor_units: true, decimal_places: 1) ==> "122¢" $ usd.format_short(1.219, as_minor_units: true, decimal_places: 3) ==> "121.9¢" $ usd.format_explicit(0.75, as_minor_units: true) ==> "75¢ USD" $ eur.format_short(0.75, as_minor_units: true) ==> "€0.75" ``` -------------------------------- ### Accessing ISO Currency Codes (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates how to retrieve ISO 4217 alpha-three and numeric-three currency codes using the `Worldwide.currency` method. It demonstrates instantiating a currency object by either its string or numeric ISO code and then accessing the corresponding code. ```Ruby $ Worldwide.currency(code: "USD").numeric_code => 840 $ Worldwide.currency(code: 840).currency_code => "USD" ``` -------------------------------- ### Configuring I18n with Top 25 Locales Source: https://github.com/shopify/worldwide/blob/main/README.md Configures the `ruby-i18n` gem to use the top 25 most common locales, as defined by `Worldwide::Locales.top_25`. `Worldwide::Config.configure_i18n` then sets up I18n with necessary fallbacks and derived locales, optimizing for common language sets while minimizing runtime overhead. ```Ruby I18n.available_locales = Worldwide::Locales.top_25 Worldwide::Config.configure_i18n ``` -------------------------------- ### Configuring I18n with All Known Locales Source: https://github.com/shopify/worldwide/blob/main/README.md Configures the `ruby-i18n` gem to support all locales known to Unicode CLDR, as provided by `Worldwide::Locales.known`. This ensures comprehensive language support across all available locales but comes with increased runtime overhead in terms of CPU and RAM usage. ```Ruby I18n.available_locales = Worldwide::Locales.known Worldwide::Config.configure_i18n ``` -------------------------------- ### Verifying Bundled Package - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Commands to verify the correctness of the bundled npm package using `publint` and `arethetypeswrong`. These tools help ensure the package is well-formed and its types are correctly exposed, especially after changes to the Rollup configuration. ```Shell pnpm package:publint pnpm package:attw ``` -------------------------------- ### Listing and Mapping All Countries in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates how to retrieve a collection of all entities considered 'countries' (territories) in the current locale. It shows how to filter for country objects, map their full names into an array, and create a hash mapping ISO codes to full names. ```Ruby Worldwide::Regions.all.select{|r| r.country?} Worldwide::Regions.all.select{|r| r.country?}.map(&:full_name) Worldwide::Regions.all.select{|r| r.country?}.each_with_object({}) { |country, hash| hash[country.iso_code] = country.full_name } ``` -------------------------------- ### Formatting Units: Japanese Locale (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates formatting a unit in a specific locale (Japanese). It uses I18n.with_locale(:ja) to temporarily set the locale, ensuring the unit is translated and formatted according to Japanese conventions. ```Ruby I18n.with_locale(:ja) { Worldwide.units.format(5, :kilogram, humanize: :long) } ``` -------------------------------- ### Humanizing Large Currency Amounts (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet illustrates how to humanize large currency amounts using the `humanize` option with `:short` or `:long` values for standard humanization, and `:japan` for Japanese-specific formatting. It shows how `format_short` and `format_explicit` adapt. ```Ruby $ eur = Worldwide.currency(code: "EUR") $ jpy = Worldwide.currency(code: "JPY") $ usd = Worldwide.currency(code: "USD") $ usd.format_short(10_000_000, humanize: :short) ==> "$10M" $ usd.format_short(10_000_000, humanize: :long) ==> "$10 million" $ usd.format_explicit(10_000_000, humanize: :short) ==> "$10M USD" $ jpy.format_short(12345) ==> "¥12,345" $ jpy.format_short(12345, humanize: :japan) ==> "1万2345円" ``` -------------------------------- ### Formatting Calendar Quarters in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to format a `Date` object into a calendar quarter string using `Worldwide::Calendar::Gregorian.quarter`. It also shows how to apply locale-specific formatting, such as for Simplified Chinese. ```Ruby $ Worldwide::Calendar::Gregorian.quarter(Date.current) => "Q4 2018" $ Worldwide::Calendar::Gregorian.quarter(Date.current, locale: "zh-Hans-CN") => "2018年第4季度" ``` -------------------------------- ### Handling Missing Translations: Development Environment (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates the behavior of I18n.t when a translation is missing in a development environment. It shows that a I18n::MissingTranslation exception is raised, indicating the missing key and locale. ```Ruby I18n.t('missing') ``` -------------------------------- ### Determining Pluralization Keys with Worldwide::Plurals (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to use `Worldwide.plurals.keys` to identify the pluralization keys (e.g., :one, :few, :many, :other) used for a specific locale and plural type (e.g., :cardinal). This is useful for understanding how plural forms are resolved in different internationalization systems. ```Ruby Worldwide.plurals.keys(:pl, type: :cardinal) ``` -------------------------------- ### Adding a Changelog Entry - Shell Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Command to create a new changelog entry using the `changesets` tool. This generates a new file for documenting changes, which is crucial for release management and versioning. ```Shell pnpm changeset ``` -------------------------------- ### Displaying Currency Information with Worldwide.currency in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This module provides methods to display currency names and symbols according to the specified locale. It allows for retrieving the currency symbol and a locale-appropriate label, which can be singular or plural based on the provided count, useful for displaying money amounts. ```Ruby $ currency = Worldwide.currency(code: "USD") $ currency.symbol => "$" # Use label when dealing with money amounts $ currency.label(count: 1) => "US dollar" $ currency.label(count: 2) => "US dollars" ``` -------------------------------- ### Formatting Lists with Worldwide.lists in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This module offers a way to display a list while respecting locale preferences, allowing for different joining conjunctions (e.g., 'and', 'or') and styles (e.g., 'narrow'). It ensures that lists are formatted correctly for various languages and cultural contexts. ```Ruby Worldwide.lists.format(["a", "b", "c"]) => "a, b, and c" Worldwide.lists.format(["a", "b", "c"], join: :or) => "a, b, or c" Worldwide.lists.format(["a", "b", "c"], join: :narrow) => "a, b, c" I18n.with_locale(:es) { Worldwide.lists.format(["a", "b", "c"], join: :or) } => "a, b o c" ``` -------------------------------- ### Handling Culturally-Appropriate Names with Worldwide.names in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This module provides methods to display user names while respecting locale preferences, such as ordering given and surnames appropriately and generating culturally-sensitive greetings. It ensures that names are presented in a manner that avoids offense and aligns with local customs. ```Ruby I18n.with_locale(:en) { Worldwide.names.full(given: "John", surname: "Smith") } => "John Smith" I18n.with_locale(:de) { Worldwide.names.full(given: "Max", surname: "Mustermann") } => "Max Mustermann" I18n.with_locale(:ja) { Worldwide.names.full(given: "賢", surname: "田中") } => "田中賢様" I18n.with_locale(:en) { Worldwide.names.greeting(given: "John", surname: "Smith") } => "John" I18n.with_locale(:ja) { Worldwide.names.greeting(given: "John", surname: "Smith") } => "Smith様" Worldwide.names.surname_first?("en") => false Worldwide.names.surname_first?("ja") => true ``` -------------------------------- ### Localizing Dates and Times with I18n in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to use the `I18n.l` method to format `Date` and `Time` objects. By specifying the `:long` format, it provides localized date and time strings according to the current locale settings. ```Ruby $ I18n.l(Date.current, format: :long) => "October 17, 2018" $ I18n.l(Time.current, format: :long) => "October 17, 2018, 9:54 pm" ``` -------------------------------- ### Concatenating and Splitting Address Fields (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This section demonstrates the `concatenate_address1`, `split_address1`, `concatenate_address2`, and `split_address2` methods. These methods are used to combine or separate specific address components (like street name/number or line2/neighborhood) into or from the `address1` and `address2` fields, based on country-specific rules. ```Ruby $ address = Worldwide.address(street_name: "Main Street", street_number: "123", country_code: "BR") => Worldwide::Address $ address.concatenate_address1 => "Main Street,\u00A0123" $ address = Worldwide.address(address1: "Main Street,\u00A0123", country_code: "BR") => Worldwide::Address $ address.split_address1 => { "street_name" => "Main Street", "street_number" => "123" } $ address = Worldwide.address(line2: "dpto 4", neighborhood: "Centro", country_code: "BR") => Worldwide::Address $ address.concatenate_address2 => "dpto 4,\u00A0Centro" $ address = Worldwide.address(address2: "dpto 4,\u00A0Centro", country_code: "BR") => Worldwide::Address $ address.split_address2 => { "line2" => "dpto 4", "neighborhood" => "Centro" } ``` -------------------------------- ### Formatting Paragraphs with Worldwide.punctuation.to_paragraph in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md The `to_paragraph` method takes an array of sentences, ensuring each sentence ends with a locale-appropriate full stop using `end_sentence`. It then concatenates the sentences, inserting an inter-sentence space if the current locale uses them, forming a properly formatted paragraph. ```Ruby $ Worldwide.punctuation.to_paragraph(["See Spot", "See Spot run.", "Run, Spot, run"]) => "See Spot. See Spot run. Run, Spot, run." $ I18n.with_locale(:ja) { Worldwide.punctuation.to_paragraph(["スポットを見る", "スポットが走る。", "早く走る。"])} => "スポットを見る。スポットが走る。早く走る。" ``` -------------------------------- ### Retrieving Zones for a Country (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to retrieve an array of `Region` objects representing zones (provinces/states) for a given country code. The zones are ordered conventionally if applicable, otherwise by name based on the current locale. ```Ruby $ Worldwide.region(code: "CA").zones => [ Worldwide::Region , Worldwide::Region ] ``` -------------------------------- ### Retrieving Region Information by Code in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to retrieve region objects and their full or short names using various codes. It covers continent, country, and subdivision codes, including chained lookups for nested regions, and shows how to handle requests for non-existent regions. ```Ruby Worldwide.region(code: "001").full_name Worldwide.region(code: "003").full_name Worldwide.region(code: "CA").full_name Worldwide.region(code: "CA-ON").full_name Worldwide.region(code: "CA").zone(code: "ON").full_name Worldwide.region(code: "001").zone(code: "003").zone(code: "021").zone(code: "CA").zone(code: "ON").full_name Worldwide.region(code: "CA-ON").short_name Worldwide.region(code: "JP-13").full_name Worldwide.region(code: "JP-13").short_name unknown = Worldwide.region(code: "bogus-does-not-exist") unknown.full_name unknown.iso_code ``` -------------------------------- ### Looking Up Country Objects by ISO Code in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to retrieve a specific Worldwide::Region object for a country using its ISO 3166-1 code. It supports various ISO formats including alpha-2, alpha-3, and numeric-3 codes for robust lookup. ```Ruby Worldwide.region(code: "BR") Worldwide.region(code: "BRA") Worldwide.region(code: "076") ``` -------------------------------- ### Formatting Units: Full-Word Kilogram (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet shows how to format a numerical value with the full-word version of a unit. By passing humanize: :long to Worldwide.units.format, the unit is displayed in its complete, human-readable form. ```Ruby Worldwide.units.format(5, :kilogram, humanize: :long) ``` -------------------------------- ### Retrieving Country Attributes (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to instantiate a `Region` object for a specific country (Canada) and access various attributes such as `full_name`, `iso_code`, `alpha_three`, and `numeric_three`. These attributes provide different representations of the region's identity. ```Ruby $ ca = Worldwide.region(code: "CA") => # $ ca.full_name => "Canada" $ ca.iso_code => "CA" $ ca.alpha_three => "CAN" $ ca.numeric_three => "124" ``` -------------------------------- ### Mapping Deprecated Timezone Names to Modern Names in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to map deprecated time zone names to their modern, supported equivalents using `Worldwide::DeprecatedTimeZoneMapper.to_supported`. This is crucial for ensuring compatibility with browsers that may not support older names, preventing JavaScript exceptions. ```Ruby mapped_zone = Worldwide::DeprecatedTimeZoneMapper.to_supported(time_zone) ``` -------------------------------- ### Identifying Script: Japanese Text (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates identifying multiple scripts within a Japanese text string using Worldwide::Scripts.identify. It correctly identifies both Han (Kanji) and Hiragana scripts present in the input. ```Ruby Worldwide::Scripts.identify(text: "日本語がわかります。") ``` -------------------------------- ### Accessing Continent Zones and Localized Names (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This code illustrates how to retrieve a continent region (e.g., North America using code "021"), access its constituent zones (countries), and map their ISO codes and full names. It also shows how to fetch localized names using `I18n.with_locale`. ```Ruby $ na = Worldwide.region(code: "021") => # $ na.zones => [#, # ... ] $ na.zones.map { |zone| [zone.iso_code, zone.full_name] } => [["CA", "Canada"], ["US", "United States"] ... ] $ I18n.with_locale(:ja) { na.zones.map { |zone| [zone.iso_code, zone.full_name] } } => [["CA", "カナダ"], ["US", "アメリカ合衆国"] ... ] ``` -------------------------------- ### Demonstrating I18n::InvalidLocale Error Source: https://github.com/shopify/worldwide/blob/main/README.md This Ruby snippet attempts to fetch a currency name using the `:fr` locale without it being explicitly loaded, which results in an `I18n::InvalidLocale` error. This illustrates the importance of explicitly setting `I18n.available_locales` before using `Worldwide::Config.configure_i18n` to avoid runtime errors. ```Ruby I18n.with_locale(:fr) { Worldwide.currency(code: "CAD").name } ``` -------------------------------- ### Formatting Units: Abbreviated Kilogram (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to format a numerical value with an abbreviated unit using the Worldwide.units.format method. It takes the value and the unit symbol as arguments, returning a string with the formatted unit. ```Ruby Worldwide.units.format(5, :kilogram) ``` -------------------------------- ### Identifying Script: Latin Text (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet shows how to identify the script of a given English text using Worldwide::Scripts.identify. It returns an array of symbols representing the identified scripts, in this case, :Latn for Latin. ```Ruby Worldwide::Scripts.identify(text: "The quick brown fox jumps") ``` -------------------------------- ### Defining Combined Address Format in YAML Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md This YAML snippet defines how address fields like `address1` and `address2` should be combined for Brazil. It specifies the `key` for each field and an optional `decorator` to be inserted between them when concatenating. ```YAML combined_address_format: address1: - key: streetName - key: streetNumber decorator: ", " address2: - key: line2 - key: neighborhood decorator: ", " ``` -------------------------------- ### Formatting Units: Plural Unit Symbol (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates that the Worldwide.units.format method can accept the plural form of a unit symbol (e.g., :kilograms) and still correctly format the value with the abbreviated unit. ```Ruby Worldwide.units.format(5, :kilograms) ``` -------------------------------- ### Concatenating Address1 for Brazil (Single Call) - TypeScript Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Demonstrates how to use `concatenateAddress1` to combine `streetName` and `streetNumber` into a single `address1` string for Brazil, based on the `combined_address_format` defined in the region's YAML. ```TypeScript concatenateAddress1({ countryCode: 'BR', streetName: 'Av. Paulista', streetNumber: '1578', }); // returns 'Av. Paulista, \u20601578' ``` -------------------------------- ### Looking Up Region by Name in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet shows how to retrieve a Worldwide::Region object by its full name. A critical warning is included, advising against this method unless absolutely necessary due to potential failures caused by variations in country names and limited support for all forms. ```Ruby Worldwide.region(name: "Brazil") ``` -------------------------------- ### Applying High-Confidence Address Autocorrection in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how `Worldwide.address` automatically corrects common address typos (e.g., zip codes, country codes) and validates addresses. It shows that even initially invalid addresses can be considered valid if they can be autocorrected into a valid form through normalization. ```Ruby $ typo_address = Worldwide.address( first_name: "John", last_name: "Doe", address1: "2370 Lancaster Rd", city: "Ottawa", province_code: "ON", zip: "k181ao", # 8 should be B, o should be 0 country_code: "CA" ) => Worldwide::Address $ typo_address.valid? => true # We consider in valid because we can autocorrect into something valid $ typo_address.normalize.zip => "K1B 1A0" $ jersey_address = Worldwide.address( first_name: "John", last_name: "Smith", address1: "The Weighbridge", city: "St. Helier", zip: "JE2 3NG", country_code: "GB", # GB is the United Kingdom, but Jersey is not in the UK. It has its own code, JE. ) => Worldwide::Address $ jersey_address.country_code => "GB" $ jersey_address.normalize.country_code => "JE" ``` -------------------------------- ### Looking Up Region by CLDR Code in Ruby Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet demonstrates how to retrieve a Worldwide::Region object using an internal Unicode CLDR code. It highlights that CLDR codes must be passed explicitly via the `cldr:` argument to avoid ambiguity with ISO codes, which might share similar string patterns. ```Ruby Worldwide.region(cldr: "caon") Worldwide.region(code: "are") Worldwide.region(cldr: "are") ``` -------------------------------- ### Concatenating Address Fields - TypeScript Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Illustrates the use of `concatenateAddress1` and `concatenateAddress2` functions. It shows how to generate combined address strings for countries with defined formats (like Brazil) and how the functions gracefully handle countries without specific `combined_address_format` by returning the original `address1` or `address2`. ```TypeScript import {concatenateAddress1, concatenateAddress2} from '@shopify/worldwide'; // Generate Address1 concatenateAddress1({ countryCode: 'BR', streetName: 'Av. Paulista', streetNumber: '1578', }); // returns 'Av. Paulista, \u20601578' concatenateAddress1({ countryCode: 'US', address1: '123 Main', }); // returns '123 Main' // Generate Address2 concatenateAddress2({ countryCode: 'BR', line2: 'dpto 4', neighborhood: 'Centro', }); // returns 'dpto 4, \u2060Centro' concatenateAddress2({ countryCode: 'US', address2: 'Apt 2', }); // returns 'Apt 2' ``` -------------------------------- ### Parsing Concatenated Address1 for Brazil (Single Call) - TypeScript Source: https://github.com/shopify/worldwide/blob/main/lang/typescript/README.md Shows how to use `splitAddress1` to parse a concatenated address string for Brazil, returning a partial address object with matched fields like `streetName` and `streetNumber`. ```TypeScript splitAddress1('BR', 'Av. Paulista, \u20601578'); // returns { streetName: 'Av. Paulista', streetNumber: '1578' } ``` -------------------------------- ### Performing Regional Zip Code Validations (Ruby) Source: https://github.com/shopify/worldwide/blob/main/README.md This snippet illustrates how to validate a zip code against a country or a specific zone within a country. It shows that a zip code can be valid for a country but invalid for a particular province/state within that country. ```Ruby $ Worldwide.region(code: "CA").valid_zip?("K1A 1A1") => true $ Worldwide.region(code: "CA").zone(code: "ON").valid_zip?("K1A 1A1") => true $ Worldwide.region(code: "CA").zone(code: "MB").valid_zip?("K1A 1A1") => false ```