module NaturalEarth::ISO3166

Public Instance Methods

as_iso3166_1(iso3166) click to toggle source

Normalize an ISO-3166-1 code (alpha-2, alpha-3 or numeric) or ISO-3166-2 code to ISO-3166 alpha-2

# File lib/natural_earth/iso3166.rb, line 6
def as_iso3166_1(iso3166)
  return numeric_to_alpha2(iso3166) if numeric? iso3166

  normalized = extract(reformat(iso3166))
  raise ArgumentError if normalized.length > 3 || normalized.length < 2

  return alpha3_to_alpha2(normalized) if normalized.length == 3

  normalized
end
as_iso3166_2(iso3166) click to toggle source

Normalize an ISO-3166-2 code

# File lib/natural_earth/iso3166.rb, line 18
def as_iso3166_2(iso3166)
  normalized = reformat(iso3166)
  raise ArgumentError unless normalized.match?(/\A[A-Z]{2}-[A-Z0-9]+\z/)

  normalized
end

Protected Instance Methods

alpha3_to_alpha2(code) click to toggle source
# File lib/natural_earth/iso3166.rb, line 41
def alpha3_to_alpha2(code)
  as_string = code.to_s
  raise ArgumentError unless alpha3_to_alpha2_map.key? as_string

  alpha3_to_alpha2_map[as_string]
end
alpha3_to_alpha2_map() click to toggle source
# File lib/natural_earth/iso3166.rb, line 55
def alpha3_to_alpha2_map
  @alpha3_to_alpha2_map ||= COUNTRIES.each_with_object({}) do |(_, c), n|
    n[c.dig('iso-3166-1', 'alpha-3')] = c.dig('iso-3166-1', 'alpha-2')
  end.freeze
end
extract(code) click to toggle source
# File lib/natural_earth/iso3166.rb, line 31
def extract(code)
  return code.split('-').first if code.match?(/-/)

  code
end
numeric?(code) click to toggle source
# File lib/natural_earth/iso3166.rb, line 37
def numeric?(code)
  code.is_a?(Numeric) || code.to_s.to_i.to_s == code
end
numeric_to_alpha2(code) click to toggle source
# File lib/natural_earth/iso3166.rb, line 48
def numeric_to_alpha2(code)
  as_int = code.to_i
  raise ArgumentError unless numeric_to_alpha2_map.key? as_int

  numeric_to_alpha2_map[as_int]
end
numeric_to_alpha2_map() click to toggle source
# File lib/natural_earth/iso3166.rb, line 61
def numeric_to_alpha2_map
  @numeric_to_alpha2_map ||= COUNTRIES.each_with_object({}) do |(_, c), n|
    n[c.dig('iso-3166-1', 'numeric')] = c.dig('iso-3166-1', 'alpha-2')
  end.freeze
end
reformat(code) click to toggle source
# File lib/natural_earth/iso3166.rb, line 27
def reformat(code)
  code.to_s.upcase.gsub('_', '-')
end