Skip to content
Better Rails Enumerations
Ruby
Find file
Latest commit 4a33b30 @DamirSvrtan DamirSvrtan Merge pull request #5 from infinum/refactor
Refactoring all around

Readme.md

Enumerations

Rails plugin for enumerations in ActiveRecord models.

Installation

Inside your Gemfile add the following:

gem 'enumerations'

Usage

Create a model for your enumerations:

class Status < Enumeration::Base
  values draft:           { id: 1, name: 'Draft' },
         review_pending:  { id: 2, name: 'Review pending' },
         published:       { id: 3, name: 'Published' }
end

Or you can use value method for defining your enumerations:

class Status < Enumeration::Base
  value :draft,           id: 1, name: 'Draft'
  value :review_pending,  id: 2, name: 'Review pending'
  value :published,       id: 3, name: 'Published'
end

Include enumerations for integer fields in other models:

class Post < ActiveRecord::Base
  enumeration :status
  validates :status_id, presence: true
end

Set enumerations, find enumerations by symbol:

@post = Post.first
@post.status = Status.find(:draft)
@post.save

Or you can set enumerations on this way:

@post.status = Status.draft

Find enumerations by id:

@post.status = Status.find(2)               # => Review pending
@post.save

Compare enumerations:

@post.status == :published                  # => true
@post.status == 3                           # => true
@post.status == Status.find(:published)     # => true
@post.status.published?                     # => true

Get all enumerations:

Status.all

Use in forms:

%p
  = f.label :status_id
  %br
  = f.collection_select :status_id, Status.all, :id, :name

Advance Usage

Except id and name you can specify other attributes to your enumerations:

class Status < Enumeration::Base
  value :draft,           id: 1, name: 'Draft'
  value :review_pending,  id: 2, name: 'Review pending', description: 'Some description...'
  value :published,       id: 3, name: 'Published'
end

Every enumeration has id, name and description methods. If you call method that is not in attribute list for enumeration, it will return nil.

Status.review_pending.description             # => 'Some description...'
Status.draft.description                      # => nil

Author

Copyright © 2010 Tomislav Car, Infinum Ltd.

Something went wrong with that request. Please try again.