0.0
No commit activity in last 3 years
No release in over 3 years
Group multiple enum values backed by ActiveRecord::Enum into scopes with ScopedEnum.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 4.1.0, ~> 4.1
~> 1.8
~> 10.0
~> 3.2
>= 1.3.10, ~> 1.3
 Project Readme

ScopedEnum

Group multiple enum values backed by ActiveRecord::Enum into scopes with ScopedEnum.

Installation

Add this line to your application's Gemfile:

gem 'scoped_enum'

And then execute:

$ bundle

Or install it yourself as:

$ gem install scoped_enum

Usage

In your ActiveRecord model:

class User < ActiveRecord::Base
    scoped_enum :role, { normal: 0, administrator: 1, superuser: 2 }, manager: [:administrator, :superuser]
end

Or you can pass in a block to create the enum scopes

class User < ActiveRecord::Base
    scoped_enum :role, { normal: 0, administrator: 1, superuser: 2 } do |e|
        e.scope :manager, [:administrator, :superuser]
    end
end

Besides stuffs created by a normal enum call, it creates three more things:

  1. An ActiveRecord scope with the same name as the enum scope.
User.create(name: 'normal', role: :normal)
User.create(name: 'administrator', role: :administrator)
User.create(name: 'superuser', role: :superuser)
User.managers #=> [<User: 'administrator'>, <User: 'superuser'>]
  1. A class method to return all scopes of an enum.
User.role_scopes #=> { manager: { administrator: 1, superuser: 2 } }
  1. An instance method to check if a record belongs to the scope.
u = User.new(role: :normal)
u.manager? #=> false
u.role = :superuser
u.manager? #=> true