Module: ISO3166::CountryClassMethods

Included in:
Country
Defined in:
lib/countries/country/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#all(&blk) ⇒ Object Also known as: countries



28
29
30
31
# File 'lib/countries/country/class_methods.rb', line 28

def all(&blk)
  blk ||= proc { |_alpha2, d| ISO3166::Country.new(d) }
  ISO3166::Data.cache.map(&blk)
end

#all_names_with_codes(locale = 'en') ⇒ Object



35
36
37
38
39
40
# File 'lib/countries/country/class_methods.rb', line 35

def all_names_with_codes(locale = 'en')
  Country.all.map do |c|
    lc = (c.translation(locale) || c.iso_short_name)
    [lc.respond_to?('html_safe') ? lc.html_safe : lc, c.alpha2]
  end.sort
end

#all_translated(locale = 'en') ⇒ Object



48
49
50
# File 'lib/countries/country/class_methods.rb', line 48

def all_translated(locale = 'en')
  translations(locale).values
end

#codesObject



24
25
26
# File 'lib/countries/country/class_methods.rb', line 24

def codes
  ISO3166::Data.codes
end

#new(country_data) ⇒ Object



20
21
22
# File 'lib/countries/country/class_methods.rb', line 20

def new(country_data)
  super if country_data.is_a?(Hash) || codes.include?(country_data.to_s.upcase)
end

#pluck(*attributes) ⇒ Object



42
43
44
45
46
# File 'lib/countries/country/class_methods.rb', line 42

def pluck(*attributes)
  all.map do |country|
    attributes.map { |attribute| country.data.fetch(attribute.to_s) }
  end
end

#translations(locale = 'en') ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/countries/country/class_methods.rb', line 52

def translations(locale = 'en')
  locale = locale.downcase
  file_path = ISO3166::Data.datafile_path(%W[locales #{locale}.json])
  translations = JSON.parse(File.read(file_path))

  custom_countries = {}
  (ISO3166::Data.codes - ISO3166::Data.loaded_codes).each do |code|
    country = ISO3166::Country[code]
    translation = country.translations[locale] || country.iso_short_name
    custom_countries[code] = translation
  end

  translations.merge(custom_countries)
end