Sha256: 0a88fb658b97d3021167f238405b23c9505a17473153a20a48507eb69ccf836d

Contents?: true

Size: 1.13 KB

Versions: 9

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module MrCommon
  class Country
    class << self
      def all(top = [])
        all_countries = label_value_pairs.dup

        top.reverse_each do |alpha2|
          all_countries = promote_one(all_countries, alpha2)
        end

        all_countries
      end

      def codes
        Carmen::Country.all.map(&:code).sort
      end

      def names
        Carmen::Country.all.map(&:name).sort
      end

      def name_for(code)
        Carmen::Country.alpha_2_coded(code).name
      end

      private

        def promote_one(collection, promoted_alpha2)
          if found_index = alpha_2_index(collection, promoted_alpha2)
            collection.unshift(collection.delete_at(found_index))
          else
            collection
          end
        end

        def alpha_2_index(collection, alpha_2)
          collection.find_index do |name_code_pair|
            name_code_pair.second == alpha_2.to_s.upcase
          end
        end

        def label_value_pairs
          @label_value_pairs ||= Carmen::Country.all.sort_by(&:name).map do |c|
            [c.name, c.code]
          end
        end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
mr_common-1.3.0 app/models/mr_common/country.rb
mr_common-1.2.0 app/models/mr_common/country.rb
mr_common-1.1.0 app/models/mr_common/country.rb
mr_common-1.0.5 app/models/mr_common/country.rb
mr_common-1.0.4 app/models/mr_common/country.rb
mr_common-1.0.3 app/models/mr_common/country.rb
mr_common-1.0.2 app/models/mr_common/country.rb
mr_common-1.0.1 app/models/mr_common/country.rb
mr_common-1.0.0 app/models/mr_common/country.rb