Enumerable Constants

Enumerable Constants provides a nice simple way of specifying that an Active Record model object attribute should be tied to a particular set of values. The act of specifying this dynamically generates code to

  • handle validation
  • provide a nice way of getting the list of values and descriptions (useful for UI stuff)
  • give easy access to constant values

Examples

Model definition:

class Property < ActiveRecord::Base
  enumerable_constant :type, :constants => [:rental, :for_sale, :auction]
end

Some view code:

<p><label for="property_type">Property Type</label><br/>
< %= collection_select(:property, :type, Property::Type.constants, :id, :title, {:prompt => 'Select a Property Type'})  % ><br />

Note the use of Property::Type.constants in place of where you would normally use a collection object like @suburbs

Some code that tests the value

property = Property.find :first
if property.type == Property::Type::FOR_SALE
  # do some stuff
end

Other things you can access

>> Property::Type.constants.first.name
=> "RENTAL"
>> Property::Type.constants.first.title
=> "Rental"
>> Property::Type.constants.first.value
=> 1

Licence

Enumerable Constants is released under the MIT licence.

Download / Install

The code can be downloaded from the subversion repository: svn://rubygreenblue.com/rubygreenblue_opensource/enumerable_constants/trunk

install as a plugin

script/plugin install svn://rubygreenblue.com/rubygreenblue_opensource/enumerable_constants/trunk