class User < ActiveRecord::Base | |
acts_as_authentic # I use authlogic | |
scope :with_role, lambda { |role| {:conditions => "roles_mask & #{1 << ROLES.index(role.to_s)} > 0"} } | |
ROLES = %w[admin manager client coordinator employee volunteer] | |
ROLE_DESCRIPTIONS = { | |
:admin => "Administers the entire site", | |
:manager => "Manages the entire site", | |
:client => "Views welcome page and own reports", | |
:coordinator => "Can view all employee assignments", | |
:employee => "Can view the entire site", | |
:volunteer => "Can add/delete volunteers", | |
} | |
ROLEGROUPS = Hash.new(0) | |
ROLES.each { |r| ROLEGROUPS[r.split('_').first.to_sym] += 1 << ROLES.index(r) } | |
def role_group?(group) | |
!((roles_mask || 0) & ROLEGROUPS[group.to_sym]).zero? | |
end | |
def roles=(roles) | |
self.roles_mask = ([*roles] & ROLES).inject(0) { |sum,r| sum += 1 << ROLES.index(r) } | |
end | |
def roles | |
ROLES.reject { |r| (roles_mask || 0)[ROLES.index(r)].zero? } | |
end | |
def role?(role) | |
i = ROLES.index(role.to_s) | |
i ? (roles_mask[i] == 1) : nil | |
end | |
def has_all_roles?(*roles) | |
has_all = true | |
([*roles] & ROLES).each do |role| | |
i = ROLES.index(role.to_s) | |
has_any = false if roles_mask[i] != 1 | |
end | |
has_all | |
end | |
def has_any_role?(*roles) | |
has_any = false | |
([*roles.map(&:to_s)] & ROLES).each do |role| | |
i = ROLES.index(role.to_s) | |
has_any = true if roles_mask[i] == 1 | |
end | |
has_any | |
end | |
def self.role_mask(role) | |
1 << (ROLES.index(role.to_s) || -1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment