Module: AttrEnumerator::ClassMethods

Defined in:
lib/attr_enumerator.rb

Instance Method Summary collapse

Instance Method Details

#attr_enumerator(attribute, choices, options = {}) ⇒ Object


8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/attr_enumerator.rb', line 8

def attr_enumerator(attribute, choices, options = {})
  constant = options.delete(:constant) || attribute.to_s.pluralize.upcase
  prefix = options[:prefix] ? options.delete(:prefix).to_s + '_' : ''
  options[:message] ||= :invalid

  const_set(constant, choices).freeze
  validates_inclusion_of attribute, options.merge(:in => choices)

  choices.each do |choice|
    choice_string = prefix + choice.to_s.underscore.parameterize('_')
    define_method(choice_string + '?') { send(attribute) == choice }
    scope choice_string, lambda { where(attribute => choice) } if respond_to? :scope
  end
end