attr_enumerator

A method for restricting an attribute to a set of choices.

An invocation of attr_enumerator will create:

Example

class Car < ActiveRecord::Base
  attr_enumerator :color, ['red', 'blue']
end

# constant
Car::COLORS           # => ['red', 'blue']

# validation
car = Car.new
car.color = 'green'
car.valid?            # => false
car.errors            # => {:color => ["is invalid"]}
car.color = 'red'
car.valid?            # => true

# instance methods
car.red?              # => true
car.blue?             # => false

# scopes
car.save
Car.red               # => [<#Car>]

With or without ActiveRecord

The AttrEnumerator module will be automatically included in ActiveRecord::Base, making the attr_enumerator method available in all ActiveRecord models.

To include AttrEnumerator on a non-ActiveRecord model the class must also include ActiveModel::Validations and provide an accessor to the attribute. The model will have all the above functionality except no scopes will be generated.

class Car
  include ActiveModel::Validations
  include AttrEnumerator

  attr_accessor :color
  attr_enumerator :color, ['red', 'blue']
end

Configuration

Options may be passed as the last argument to attr_enumerator to configure its behavior. For example:

class Car < ActiveRecord::Base
  attr_enumerator :color, ['red', 'blue'], :constant => :PAINT_COLORS, :prefix => :painted
end

Car::PAINT_COLORS   # => ['red', 'blue']

car = Car.new
car.color = 'red'
car.painted_red?    # => true

Options

Contributing to attr_enumerator