Could someone please explain this code, this is the same blog app explained
on github but I could not understand the use of this part specially the use of name spaces role mask.
There are three roles in this app admin, moderator and author.
Based on the CRUD functionality they are able to edit comments or delete a comment.
class User < ActiveRecord::Base
acts_as_authentic
has_many :articles
has_many :comments
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
ROLES = %w[admin moderator author]
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def role_symbols
roles.map(&:to_sym)
end
end
The
role_maskis a bitfield. Whenever roles get assigned to theUser, therole_maskautomatically gets updated. The possible values for the roles mask and respective roles:The bitfield is used to quickly search the database for users with a specific role. This is done by applying
&operator on therole_maskwith the bitfield of the role you are looking for. For example, to get all users who are authors, thewith_rolescope does a database query for all records for whichroles_mask & 100is true.