[FLOSS Week]: enum_field
Posted by: Mathieu Martin on 2009-02-17
This release announcement is part of FLOSS week.
At GiraffeSoft, we love DRY code. That's why we're very quick at creating small plugins that encapsulate the way we code.
Today I'll unveil one such plugin. It's a very simple one that lets you specify an enum field for an ActiveRecord model.
The plugin of course encapsulates a standard validates_inclusion_of
class Computer < ActiveRecord::Base
validates_inclusion_of :status, :in =>
['on', 'off', 'standby', 'sleep', 'out of this world']
#...
end
But then it adds a few nifty extras that just make sense. So using the enum_field plugin:
class Computer < ActiveRecord::Base
enum_field :status,
['on', 'off', 'standby', 'sleep', 'out of this world']
#...
end
gives us a bunch useful things:
- add a validates_inclusion_of with a simple error message ("invalid #{field}")
- define the following query methods, in the name of expressive code:
- on?
- off?
- standby?
- sleep?
- out_of_this_world?
- define the Computer::STATUSES constant, which contains all acceptable values
This plugin has been known to work very well with other plugins. For example, we've used it successfully with Phusion's excellent default_value_for plugin.
class Computer < ActiveRecord::Base
enum_field :status,
['on', 'off', 'standby', 'sleep', 'out of this world']
default_value_for :status, 'off'
#...
end
If you don't like the default error message, you can of course override it with an additional :message option.
enum_field :status,
['on', 'off', 'standby', 'sleep', 'out of this world'],
:message => "incorrect status"
Get it
You can install it inside your app either as a plugin:
$ script/plugin install git://github.com/giraffesoft/enum_field.git
or as a gem, add the following line in you config/environment.rb:
config.gem "giraffesoft-enum_field", :lib => "enum_field",
:source => "http://gems.github.com"
or of course, fork it on GitHub
Conclusion
This is a good general purpose plugin to include in one's customized Rails app generator. We may add it to blank in the future, if we find we're frequently adding it to new projects.
This release announcement is part of FLOSS week. If you're interested in more open source software, consider subscribing or following us on twitter to get the next announcements asap.

