class CountryToLocalesMapping::Mapping

TODO: Give each locale a preference value: e.g. de-CH 0.6, fr-CH 0.3

Attributes

cc[RW]
ll[RW]

Public Class Methods

new() click to toggle source
# File lib/country_to_locales_mapping/mapping.rb, line 43
def initialize
  @cc = {}
  @ll = {}
  import_locale_map
end

Public Instance Methods

country_code_locales(c) click to toggle source

Returns an array of locale ids that match the given country code.

# File lib/country_to_locales_mapping/mapping.rb, line 78
def country_code_locales(c)
  if c.nil? || !@cc.has_key?(c)
    raise ArgumentError, "Country code not recognized: #{c}"
  end

  @cc[c][:locales]
end
import_locale_map() click to toggle source

Imports country-locale map to memory for upcoming queries

# File lib/country_to_locales_mapping/mapping.rb, line 51
def import_locale_map
  json = JSON.parse(File.read(path_to_json))

  json["countries"].each_pair do |country_code, country_data|
    country_name = country_data["name"]
    languages = country_data["locales"]

    associate_country_with_locales(country_name, country_code, languages)
  end
end
locale_country_codes(l) click to toggle source

Returns an array of country codes that match the given locale code.

Note: Since in our current mapping, “en” is not assigned to any country, so “en” will not match anything while “en-us” will return “us”.

# File lib/country_to_locales_mapping/mapping.rb, line 68
def locale_country_codes(l)
  if l.nil? || !@ll.has_key?(l)
    raise ArgumentError, "Locale not recognized: #{l}"
  end

  @ll[l][:ccodes]
end

Private Instance Methods

associate_country_with_locales(country_name, country_code, languages) click to toggle source
# File lib/country_to_locales_mapping/mapping.rb, line 88
def associate_country_with_locales(country_name, country_code, languages)
  @cc[country_code] = {
    name: country_name,
    locales: languages,
  }

  languages.each do |l|
    @ll[l] ||= {}
    @ll[l][:ccodes] ||= []
    @ll[l][:ccodes].push country_code
  end
end
path_to_json() click to toggle source
# File lib/country_to_locales_mapping/mapping.rb, line 101
def path_to_json
  File.expand_path("../../../data/country_locale_map.json", __FILE__)
end