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:
- 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'>]
- A class method to return all scopes of an enum.
User.role_scopes #=> { manager: { administrator: 1, superuser: 2 } }
- 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