Sha256: 8b000f30cc0bb1e38c168b33792dbb6d90324f303ef274ecd0b33af51b171fce

Contents?: true

Size: 1.31 KB

Versions: 35

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

require "forwardable"
require "singleton"
require "yaml"

require "worldwide/regions_loader"

module Worldwide
  class Regions
    include Singleton

    class << self
      extend Forwardable
      def_delegators :instance, :all, :region_by_cldr_code, :region
    end

    def initialize
      @regions, @regions_by_cldr_code, @regions_by_iso_code = RegionsLoader.new.load_regions
    end

    def all
      @regions
    end

    def region(cldr: nil, code: nil, name: nil)
      unless exactly_one_present?(cldr, code, name)
        raise ArgumentError, "Must specify exactly one of cldr:, code: or name:. (code: is preferred)"
      end

      result = if cldr
        @regions_by_cldr_code[cldr.to_s.upcase]
      elsif code
        @regions_by_iso_code[code.to_s.upcase]
      else # search by name
        search_name = name.upcase

        @regions.find do |r|
          r.legacy_name&.upcase == search_name || r.full_name&.upcase == search_name ||
            r.name_alternates.map(&:upcase).include?(search_name)
        end
      end

      result || Worldwide.unknown_region
    end

    private

    def exactly_one_present?(first, second, third)
      a = Util.present?(first)
      b = Util.present?(second)
      c = Util.present?(third)

      (a ^ b ^ c) && !(a && b && c)
    end
  end
end

Version data entries

35 entries across 35 versions & 1 rubygems

Version Path
worldwide-1.14.1 lib/worldwide/regions.rb
worldwide-1.14.0 lib/worldwide/regions.rb
worldwide-1.13.0 lib/worldwide/regions.rb
worldwide-1.12.0 lib/worldwide/regions.rb
worldwide-1.11.1 lib/worldwide/regions.rb
worldwide-1.11.0 lib/worldwide/regions.rb
worldwide-1.10.0 lib/worldwide/regions.rb
worldwide-1.9.0 lib/worldwide/regions.rb
worldwide-1.8.0 lib/worldwide/regions.rb
worldwide-1.7.5 lib/worldwide/regions.rb
worldwide-1.7.4 lib/worldwide/regions.rb
worldwide-1.7.3 lib/worldwide/regions.rb
worldwide-1.7.2 lib/worldwide/regions.rb
worldwide-1.7.1 lib/worldwide/regions.rb
worldwide-1.7.0 lib/worldwide/regions.rb
worldwide-1.6.2 lib/worldwide/regions.rb
worldwide-1.6.1 lib/worldwide/regions.rb
worldwide-1.6.0 lib/worldwide/regions.rb
worldwide-1.5.0 lib/worldwide/regions.rb
worldwide-1.4.1 lib/worldwide/regions.rb