David Dollar

ActiveRecord Enumerables

As part of the requirements for my Poll model in the Rails Rumble, I have a few columns that need to be locked down to certain values. Rather than repeating validates_presence_of and validates_inclusion_of over and over, I threw together a quick plugin that does both of these as well as adds some convenience methods.

You can find the plugin at http://github.com/ddollar/active-record-enumerable.git

class Food < ActiveRecord::Base
  include ActiveRecordEnumerable

  enumerate :type,  :as => %w( fruit vegetable ), :default => 'foo'
  enumerate :color, :as => %w( red green )

If :default is not specified, the first enumerator in the list is used.

>> f = Food.new
=> #<Food id: nil, type: "foo", color: "red">
>> f.save
=> true

>> f.color.red?
=> true

>> f.color.turquoise?
=> false

>> f.update_attributes!(:color => "random")
=> ActiveRecord::RecordInvalid: Validation failed: Color is not included in the list