# Author:: Maurizio Casimirri (mailto:maurizio.cas@gmail.com) # Copyright:: Copyright (c) 2012 Maurizio Casimirri # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'rails' require 'iso3166' module ActionView module Helpers module FormOptionsHelper def country_select(object, method, priority_countries = nil, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_country_select_tag(priority_countries, options, html_options) end def country_options_for_select(selected = nil, priority_countries = nil) country_options = "" if priority_countries country_options += options_for_select(priority_countries, selected) country_options += "\n" selected=nil if priority_countries.include?(selected) end countries = Iso3166.codes.map {|code| [Iso3166.localize(code), code] } return country_options + options_for_select(countries, selected) end end class InstanceTag def to_country_select_tag(priority_countries, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) content_tag("select", add_options( country_options_for_select(value, priority_countries), options, value ), html_options ) end end class FormBuilder def country_select(method, priority_countries = nil, options = {}, html_options = {}) @template.country_select(@object_name, method, priority_countries, options.merge(:object => @object), html_options) end end end end module IsoCountrySelect extend ActiveSupport::Concern def country_name(code) Iso3166.localize(code) end end ActionView::Base.send :include, IsoCountrySelect