Module: LocalizedCountrySelect

Defined in:
lib/localized_country_select.rb

Overview

LocalizedCountrySelect

View helper for displaying select list with countries:

country_select(:user, :country)

Works just like the default Rails’ country_select plugin, but stores countries as country codes, not names, in the database.

You can easily translate country codes in your application like this:

<%= I18n.t @user.country, :scope => 'countries' %>

Uses the Rails internationalization framework (I18n) for translating the names of countries.

Use Rake task rake import:country_select 'de' for importing country names from Unicode.org’s CLDR repository (www.unicode.org/cldr/data/charts/summary/root.html)

Code adapted from Rails’ default country_select plugin (previously in core) See github.com/rails/country_select/tree/master/lib/country_select.rb

Class Method Summary collapse

Class Method Details

.localized_countries_array(options = {}) ⇒ Object

Returns array with codes and localized country names (according to I18n.locale) for <option> tags



29
30
31
32
33
34
35
# File 'lib/localized_country_select.rb', line 29

def localized_countries_array(options = {})
  if options[:description] == :abbreviated
    I18n.translate(:countries).map { |key, value| [key.to_s.upcase] }.sort_by { |country| country.first }
  else
    I18n.translate(:countries).map { |key, value| [value, key.to_s.upcase] }.sort_by { |country| country.first }
  end
end

.priority_countries_array(country_codes = [], options = {}) ⇒ Object

Return array with codes and localized country names for array of country codes passed as argument

Example

priority_countries_array([:TW, :CN])
# => [ ['Taiwan', 'TW'], ['China', 'CN'] ]


41
42
43
44
45
46
47
48
# File 'lib/localized_country_select.rb', line 41

def priority_countries_array(country_codes = [], options = {})
  if options[:description] == :abbreviated
    country_codes.map { |code| [code.to_s.upcase] }
  else
    countries = I18n.translate(:countries)
    country_codes.map { |code| [countries[code.to_s.upcase.to_sym], code.to_s.upcase] }
  end
end