Skip to content

Instantly share code, notes, and snippets.

@iMagesh
Last active August 29, 2015 13:57
Show Gist options
  • Save iMagesh/9615623 to your computer and use it in GitHub Desktop.
Save iMagesh/9615623 to your computer and use it in GitHub Desktop.
User Model roles
require 'csv'
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable, :token_authenticatable,
:recoverable, :rememberable, :trackable, :authentication_keys => [:rollno]
# Roles initialization
ROLES = [ :admin, :student, :assistant, :professor ]
mask = {:student => [2], :admin => [1], :assistant => [4], :professor => [8] }
scope :find_by_roles, lambda {|role|
u = User.where("roles_mask IN(?)", mask[role.to_sym]) #.order(:first_name)
}
def roles=(roles)
self.roles_mask = (roles.map(&:to_sym) & User::ROLES).map { |r| 2**User::ROLES.index(r) }.sum
self.save
end
def roles
User::ROLES.reject { |r| ((roles_mask || 0) & 2**User::ROLES.index(r)).zero? }
end
def add_roles(*args)
raise ArgumentError.new('You must to specify additional roles within User::ROLES.') if args.map { |role| User::ROLES.include?(role.to_sym) }.include?(false)
args.map { |role| roles.include?(role.to_sym) ? false : self.roles = roles << role.to_sym }
roles
end
def remove_roles(*args)
if args.nil? || args.empty?
self.update_attribute(:roles_mask, nil)
else
self.roles = roles.delete_if { |e| args.map(&:to_sym).include?(e) }
end
end
def is_admin?
! ([:admin] & roles).blank?
end
def is_student?
! ([:student] & roles).blank?
end
def is_assistant?
! ([:assistant] & roles).blank?
end
def is_professor?
! ([:professor] & roles).blank?
end
def approve!
update_attribute(:approved,true)
end
def deactivate!
update_attribute(:approved,false)
end
# Methods for devise
def active_for_authentication?
super && approved?
end
def inactive_message
if !approved?
:not_approved
else
super # Use whatever other message
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment