Rails plugin that creates constants and helper methods for attributes that are enums
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.document
.gitignore
MIT-LICENSE
README.rdoc
Rakefile
init.rb

README.rdoc

EnumHelper

For columns in Rails models (or attributes in any class) this plugin provides support for enumerated values including:

  • defining constants

  • defining predicate methods

  • defining other constants

  • defining other related methods

  • specifying Rails validates_inclusion_of validation

Other enum-related plugins that might be a better fit for your needs:

Documentation

API documentation at {rdoc.info/projects/stevedowney/enum_helper}

Example

class Person < ActiveRecord::Base
  enum_helper :sex, %w(male female)
end

# constants

Person::SEXES       #=> ["male", "female"]
Person::SEX_MALE    #=> "male"
Person::SEX_FEMALE  #=> "female"

guy = Person.new(:sex => SEX_MALE)  #=> #<Person id: nil, sex: "male">

# predicate methods

guy.sex_male?                     #=> true
guy.sex_female?                   #=> false

# validates_inclusion_of by default

guy.valid?           #=> true
guy.status = 'foo'
guy.valid?           #=> false

Tip

If you are having trouble figuring out what constants and methods are getting generated, try:

MyClass.constants
MyClass.new.methods

or if too much is returned:

MyClass.constants.grep(/<search term>/i).sort
MyClass.new.methods.grep(/<search term>/i).sort

TODO

  • named scopes (:value, :not_value)

  • support: not_foo? not 'foo'

  • enum_select(:field)

  • valid? / :allow_nil => true/false

Copyright

Copyright © 2010 Steve Downey, released under the MIT license