Sha256: ea091790075dd8abc122e1e594917f376f0b5ed3da162d8ef9da8965e1828850

Contents?: true

Size: 1.07 KB

Versions: 2

Compression:

Stored size: 1.07 KB

Contents

class IsoCountryCodes # :nodoc:
  class UnknownCodeError < StandardError; end

  class << self

    def for_select(*args)
      Code.for_select(*args)
    end

    def all
      Code.all
    end

    def find(code, opts={})
      code     = code.to_s.upcase
      instance = nil

      if code.match(/^\d{2}$/)
        code = "0#{code}" # Make numeric codes three digits
      end

      if code.match(/^\d{3}$/)
        instance = all.select { |c| c.numeric == code }.first
      elsif code.match(/^[A-Z]{2}$/)
        instance = all.select { |c| c.alpha2 == code }.first
      elsif code.match(/^[A-Z]{3}$/)
        instance = all.select { |c| c.alpha3 == code }.first
      else
        instance = all.select { |c| c.name.upcase == code }.first
        if opts[:fuzzy]
          instance = all.select { |c| c.name.match(/^#{code}/i) }.first if instance.nil?
          instance = all.select { |c| c.name.match(/#{code}/i) }.first if instance.nil?
        end
      end

      raise UnknownCodeError, "ISO 3166-1 code '#{code}' does not exist." if instance.nil?

      instance
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
iso_country_codes-0.3.1 lib/iso_country_codes/iso_country_codes.rb
iso_country_codes-0.3.0 lib/iso_country_codes/iso_country_codes.rb