No commit activity in last 3 years
No release in over 3 years
Enumerated types for ActiveRecord attributes
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
>= 0
>= 0

Runtime

 Project Readme

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'

Custom serialization

For performance reasons, it is sometimes advantageous to store enum values as integers. This can be achieved via custom serialization.

class JobStatus
  include EnumeratedType

  declare :started, id: 1
  declare :finished, id: 2

  def self.deserialize(value)
    detect { |type| type.id == value.to_i }
  end

  def serialize
    id
  end
end

job = Job.new(status: :finished)
# => #<Job status: 2>

job.status
#<JobStatus:finished>

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

About Foraker Labs

Foraker Logo

Foraker Labs builds exciting web and mobile apps in Boulder, CO. Our work powers a wide variety of businesses with many different needs. We love open source software, and we're proud to contribute where we can. Interested to learn more? Contact us today.

This project is maintained by Foraker Labs. The names and logos of Foraker Labs are fully owned and copyright Foraker Design, LLC.