Provides a simple helper to get an HTML select list of countries using the ISO 3166-1 standard.
It is also configurable to use countries' ISO 3166-1 alpha-2 codes as values and ISO 3166-1 names as display strings.
While the ISO 3166 standard is a relatively neutral source of country names, it may still offend some users. Developers are strongly advised to evaluate the suitability of this list given their user base.
Install as a gem using
gem install country_select
Or put the following in your Gemfile
gem 'country_select'
Simple use supplying model and attribute as parameters:
country_select("user", "country")
Supplying priority countries to be placed at the top of the list:
country_select("user", "country", [ "Great Britain", "France", "Germany" ])
Country names are automatically localized based on the value of
I18n.locale
thanks to the wonderful
countries gem.
Current translations include: en, it, de, fr, es, ja, nl, but may not be complete. In the event a translation is not available, it will revert to the globally assigned locale (by default, "en").
The locale can be overridden locally:
country_select(:country_name, ['US'], {:iso_codes => true, :locale => 'es'})
You can have the option
tags use ISO 3166-1 alpha-2 codes as values
and the country names as display strings. For example, the United States
would appear as <option value="US">United States</option>
If you're starting a new project, this is the recommended way to store your country data since it will be more resistant to country names changing.
country_select("user", "country_code", nil, iso_codes: true)
country_select("user", "country_code", [ "GB", "FR", "DE" ], iso_codes: true)
Add the following configuration to an initializer.
::CountrySelect.use_iso_codes = true
class User < ActiveRecord::Base
# Assuming country_select is used with User attribute `country_code`
# This will attempt to translate the country name and use the default
# (usually English) name if no translation is available
def country_name
country = Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
end
An example Rails application demonstrating the different options is available at scudco/country_select_test. The relevant view file lives here.
bundle
bundle exec rspec
bundle exec appraisal
Copyright (c) 2008 Michael Koziarski, released under the MIT license