SimplestStatus

SimplestStatus is a gem built to provide simple, convenient status functionality for Rails models. It's designed to work with practically every version of Rails (tested as far back as 2.0.5) and will work with Ruby 1.9.3 and up.
SimplestStatus is similar to the recently introduced enum (debuted in Rails 4.1), but is different in that it doesn't rely on a particular version of Rails, it's geared specifically toward status columns, and it provides additional functionality like constant-based status lookup, label helpers, and validations.
Installation
Add this line to your application's Gemfile:
gem 'simplest_status'
And then execute:
$ bundle
Or install it yourself as:
$ gem install simplest_status
Usage
Add an integer-type status field to a model with :null => false and :default => 0:
class AddStatusToPostsMigration < ActiveRecord::Migration
def change
add_column :posts, :status, :integer, :null => false, :default => 0
end
end
Then in your model, extend SimplestStatus and list out your statuses:
class Post < ActiveRecord::Base
extend SimplestStatus
statuses :draft, :preview, :published, :archived
end
This will generate a number of constants, methods, and model validations.
Status List
Post.statuses # => { :draft => 0, :preview => 1, :published => 2, :archived => 3 }
The returned hash is a StatusCollection that, when iterated over, yields Status objects:
Post.statuses.first.tap do |status|
status.name # => :draft
status.value # => 0
status.string # => 'draft'
status.to_hash # => { :draft => 0 }
status.constant_name # => 'DRAFT'
status.label # => 'Draft'
status.for_select # => ['Draft', 0]
end
It also provides a helper method for usage in a form select:
Post.statuses.for_select # => [['Draft', 0], ['Preview', 1], ['Published', 2], ['Archived', 3]]
Constants
Instead of referring to status values by the underlying integer, SimplestStatus generates constants for this purpose:
Post::DRAFT # => 0
Post::PREVIEW # => 1
Post::PUBLISHED # => 2
Post::ARCHIVED # => 3
Scopes
Post.draft
Post.preview
Post.published
Post.archived
Predicate Methods
Post.new(:status => Post::DRAFT) do |post|
post.draft? # => true
post.preview? # => false
post.published? # => false
post.archived? # => false
end
Status Mutation Methods
Post.new(:status => Post::ARCHIVED) do
post.draft # status from Post::ARCHIVED to Post::DRAFT
post.preview # status from Post::DRAFT to Post::PREVIEW
post.published # status from Post::PREVIEW to Post::PUBLISHED
post.archived # status from Post::PUBLISHED to Post::ARCHIVED
end
Status Label Method
Post.new(:status => Post::DRAFT).status_label # => 'Draft'
Post.new(:status => Post::PREVIEW).status_label # => 'Preview'
Post.new(:status => Post::PUBLISHED).status_label # => 'Published'
Post.new(:status => Post::ARCHIVED).status_label # => 'Archived'
Status Validations
SimplestStatus will automatically add the following validations:
validates :status, :presence => true, :inclusion => { :in => proc { statuses.values } }