ActiveRecord Enumerated Type

Integrates EnumeratedType with ActiveRecord.

Installation

Add this line to your application's Gemfile:

gem 'active_record_enumerated_type'

And then execute:

$ bundle

Or install it yourself as:

$ gem install active_record_enumerated_type

Usage

1. Create a formal type

For example, per the EnumeratedType documentation, a JobStatus:

class JobStatus
  include EnumeratedType

  declare :started
  declare :finished
end

2. Restrict an ActiveRecord attribute to the type.

For example, assuming a Job class with a status attribute:

class Job < ActiveRecord::Base
  restrict_type_of :status, to: JobStatus
end

This allows one to set attributes symbolically or as formal types.

job = Job.new(status: JobStatus[:started])
job.status # => JobStatus[:started]

job = Job.new(status: :started)
job.status # => JobStatus[:started]

job = Job.new(status: nil)
job.status # => nil

Setting an invalid type raises an exception.

job = Job.new(status: :pending)
# => "'pending' is not a valid type for status. Valid types include 'started' and 'finished'."

I18n support

Type names can be translated with I18n.

en:
  enumerated_type:
    job_status:
      finished: Finito
job = Job.new(status: :finished)
job.status.human
# => 'Finito'

job = Job.new(status: :started)
job.status.human
# => 'started'

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request