Rails country select plugin
This is just another post about a a component I found myself needing for GameGrid. I needed an easy way of enabling users to specify their countries, but whilst Rails provides helpers for just about every other form element, it failed me here. The source is on GitHub, if you’re interested. The data is sourced from ISO-3166, just that it all comes from Wikipedia since the standards body are a bit…difficult.
Usage goes something like the following…
First off, checkout the master branch of the GitHub repository and stick it in your application’s vendor/plugins directory. Now, edit the app’s Gemfile to add something like so:
# http://lukecarrier.me/rails-country-select-plugin/ gem 'country-select', path: 'vendor/plugins/rails-country-select'
Once you’ve updated your bundle, you’ll be able to use this in your view (assuming you’re using ERb, which you more than likely are):
<%= form_for @model do |f| %> <!-- SNIP --> <%= f.country_select :field_name %> <!-- SNIP --> <% end %>
Note that you can optionally specify an options hash to customise the keys displayed and the values that’ll be posted back to your model. This looks a little like so (on Ruby 1.9; 1.8 likes an ugly hash syntax like { :keys => :alpha3s, :values => :names }):
<%= form_for @model do |f| %>
<!-- SNIP -->
<%= f.country_select :field_name, { keys: :alpha3s, values: :names } %>
<!-- SNIP -->
<% end %>
Valid values for the “keys” and “values” options are:
- names – the names of the country as defined in the COUNTRY_NAMES array in lib/country_definitions.rb
- alpha2s – two-character identifiers for the countries (COUNTRY_ALPHA2S)
- alpha3s – the three letter identifiers that the standards body refused to offer for a reasonable price! (COUNTRY_ALPHA3S)
- nums – the numerical IDs (COUNTRY_NUMS)
For each of the above, you’ll want to use some validations in your model to make sure your users aren’t doing crazy things. Although I plan to write some nice validation helpers at some point, for now you’ll just have to verify inclusion. How you do this depends on how you prefer your validations – modern or spaced out:
# Modern:
validates :country, inclusion: { in: COUNTRY_NUMS }
# Spaced out:
validates_inclusion_of :country, in: COUNTRY_NUMS
Et voila! There’s one more thing I worked on; using Nokogiri’s XPath functionality to directly parse Wikipedia’s table of the country mappings that make up the standard. It’s implemented as a rake task (in lib/tasks/rake.rake, for the adventurous), and can be executed like so:
rake plugin:country_select:rebuild_country_arrays
It doesn’t display any output, but it does rewrite country_definitions.rb on your behalf. After running this, I advise also running the tests to make sure the task didn’t screw up:
cd vendor/plugins/country_select ruby -I. test/country_test.rb
