Class: CountryToLocalesMapping::Mapping

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/country_to_locales_mapping/mapping.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMapping

Returns a new instance of Mapping.



43
44
45
46
47
# File 'lib/country_to_locales_mapping/mapping.rb', line 43

def initialize
  @cc = {}
  @ll = {}
  import_locale_map
end

Instance Attribute Details

#ccObject

Returns the value of attribute cc.



41
42
43
# File 'lib/country_to_locales_mapping/mapping.rb', line 41

def cc
  @cc
end

#llObject

Returns the value of attribute ll.



41
42
43
# File 'lib/country_to_locales_mapping/mapping.rb', line 41

def ll
  @ll
end

Instance Method Details

#country_code_locales(c) ⇒ Object

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



78
79
80
81
82
83
84
# 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_mapObject

Imports country-locale map to memory for upcoming queries



51
52
53
54
55
56
57
58
59
60
# 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) ⇒ Object

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”.



68
69
70
71
72
73
74
# 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