Module: CountryCodes
- Defined in:
- lib/country_select/country_codes.rb
Overview
:nodoc:
Class Method Summary collapse
- .countries_for_select(*args) ⇒ Object
- .load_countries_from_yaml ⇒ Object
- .method_missing(name, *args) ⇒ Object
- .nil_countries_hash ⇒ Object
- .valid_attributes ⇒ Object
Class Method Details
.countries_for_select(*args) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/country_select/country_codes.rb', line 29 def self.countries_for_select(*args) # Ensure that each of the arguments is a valid attribute args.each do |arg| unless valid_attributes.include?(arg) raise "#{arg} is not a valid attribute, valid attributes are: #{valid_attributes.join(', ')}" end end # Build and return the desired array @countries[@countries.keys.first].map do |index, country| args.map { |a| country[a.to_sym] } end end |
.load_countries_from_yaml ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/country_select/country_codes.rb', line 53 def self.load_countries_from_yaml # Load countries countries_from_file = YAML::load(File.open(File.(File.join(File.dirname(__FILE__), 'countries.yml')))) # Build indexes for each attribute @countries = {} countries_from_file.first.keys.each do |key| @countries[key.to_s] = {} countries_from_file.each { |country| @countries[key.to_s][country[key].to_s.downcase] = country } end end |
.method_missing(name, *args) ⇒ Object
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/country_select/country_codes.rb', line 2 def self.method_missing(name, *args) if match = /find_([^_]*)_by_([^_]*)/.match(name.to_s) raise "1 argument expected, #{args.size} provided." unless args.size == 1 required = match[1] request = match[2] if valid_attributes.include?(request) && valid_attributes.include?(required) @countries[request][args[0].to_s.downcase][required.to_sym] || nil rescue nil else raise "#{request} is not a valid attribute, valid attributes for find_*_by_* are: #{valid_attributes.join(', ')}." end elsif match = /find_by_(.*)/.match(name.to_s) raise "1 argument expected, #{args.size} provided." unless args.size == 1 request = match[1] if valid_attributes.include?(request) @countries[request][args[0].to_s.downcase] || nil_countries_hash else raise "#{request} is not a valid attribute, valid attributes for find_by_* are: #{valid_attributes.join(', ')}." end else raise NoMethodError.new("Method '#{name}' not supported") end end |
.nil_countries_hash ⇒ Object
47 48 49 50 51 |
# File 'lib/country_select/country_codes.rb', line 47 def self.nil_countries_hash hash = {} valid_attributes.map { |attribute| hash[attribute.to_sym] = nil } hash end |
.valid_attributes ⇒ Object
43 44 45 |
# File 'lib/country_select/country_codes.rb', line 43 def self.valid_attributes @countries.keys end |