Module: Enumlogic
- Defined in:
- lib/enumlogic.rb
Overview
See the enum class level method for more info.
Instance Method Summary collapse
-
#enum(field, values, options = {}) ⇒ Object
Allows you to easily specify enumerations for your models.
Instance Method Details
#enum(field, values, options = {}) ⇒ Object
Allows you to easily specify enumerations for your models. Specify enumerations like:
class Computer < ActiveRecord::Base
enum :kind, ["apple", "dell", "hp"]
enum :kind, {"apple" => "Apple", "dell" => "Dell", "hp" => "HP"}
end
You can now do the following:
Computer::KINDS # passes back exactly what you specified, Array or Hash
Computer. # gives you a friendly hash that you can easily pass into the select helper for forms
Computer.new(:kind => "unknown").valid? # false, automatically validates inclusion of the enum field
c = Computer.new(:kind => "apple")
c.apple? # true
c.apple_key # :apple
c.apple_text # "apple" or "Apple" if you gave a hash with a user friendly text value
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/enumlogic.rb', line 22 def enum(field, values, = {}) values_hash = if values.is_a?(Array) hash = {} values.each { |value| hash[value] = value } hash else values end values_array = values.is_a?(Hash) ? values.keys : values = [:message] || "#{field} is not included in the list" constant_name = [:constant] || field.to_s.pluralize.upcase const_set constant_name, values_array unless const_defined?(constant_name) new_hash = {} values_hash.each { |key, text| new_hash[text] = key } (class << self; self; end).send(:define_method, "#{field}_options") { new_hash } define_method("#{field}_key") do value = send(field) return nil if value.nil? value.to_s.gsub(/[-\s]/, '_').downcase.to_sym end define_method("#{field}_text") do value = send(field) return nil if value.nil? values_hash.find { |key, text| key == value }.last end values_array.each do |value| method_name = value.downcase.gsub(/[-\s]/, '_') method_name = "#{method_name}_#{field}" if [:namespace] define_method("#{method_name}?") do self.send(field) == value end end validates_inclusion_of field, :in => values_array, :message => , :allow_nil => [:allow_nil] end |