Easy role definition. Supported by the enumerize gem for Rails.
gem 'enja'
Optionally, you can run the generator, which will set up a role field with some useful defaults for you:
$ bin/rails g enja:install
Call define_role_field
in your resource of user model (User
, AdminUser
or Member
etc):
class User < ApplicationRecord
define_role_field :role, in: [:guest, :staff, :admin], default: :guest
end
Then it provides some convenient methods for implement role based system:
user = User.new(role: :guest)
# == Predicate Methods
user.guest? # true
user.staff? # false
user.admin? # false
# == Update Methods
user.guest! # => :guest
user.staff! # => :staff
user.admin! # => :admin
# == Scopes
User.guest.all # User.where(role: :guest).all
User.staff.all # User.where(role: :staff).all
User.admin.all # User.where(role: :admin).all
The gem is available as open source under the terms of the MIT License.