Sha256: 8893068902a613476aeccadd48571202d07d91eae22999d1b95f5c60bb1a47f7

Contents?: true

Size: 1.94 KB

Versions: 3

Compression:

Stored size: 1.94 KB

Contents

# frozen_string_literal: true

# Encapsulates the translation information for all locales, for a single field in a single country

require "yaml"

module Worldwide
  class Field
    VALID_KEYS = [
      :first_name,
      :last_name,
      :company,
      :address1,
      :street_name,
      :street_number,
      :address2,
      :line2,
      :neighborhood,
      :city,
      :province,
      :zip,
      :country,
      :phone,
      :address,
    ]

    class << self
      def valid_key?(key)
        VALID_KEYS.include?(key.to_sym)
      end
    end

    def initialize(country_code: nil, field_key:)
      @country_code = country_code&.upcase&.to_sym
      @field_key = field_key.downcase.to_sym
    end

    def autofill(locale: I18n.locale)
      lookup("autofill", locale: locale)
    end

    def label(locale: I18n.locale)
      lookup("label.default", locale: locale)
    end

    def label_marked_optional(locale: I18n.locale)
      lookup("label.optional", locale: locale)
    end

    def error(locale: I18n.locale, code:, options: {})
      lookup("errors.#{code}", locale: locale, options: options)
    end

    def warning(locale: I18n.locale, code:, options: {})
      lookup("warnings.#{code}", locale: locale, options: options)
    end

    private

    def base_key(country_key)
      "worldwide.#{country_key}.addresses.#{@field_key}"
    end

    def default_lookup(key_suffix, options: {})
      base = base_key("_default")
      I18n.t("#{base}.#{key_suffix}", default: nil, **options) ||
        I18n.with_locale(:en) { I18n.t("#{base}.#{key_suffix}", default: nil, **options) }
    end

    def lookup(key_suffix, locale:, options: {})
      I18n.with_locale(locale) do
        if @country_code.nil?
          default_lookup(key_suffix, options: options)
        else
          I18n.t("#{base_key(@country_code)}.#{key_suffix}", default: nil, **options) ||
            default_lookup(key_suffix, options: options)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
worldwide-1.0.0 lib/worldwide/field.rb
worldwide-0.15.0 lib/worldwide/field.rb
worldwide-0.14.0 lib/worldwide/field.rb