I'm having a lot of difficulty putting together what the following code is supposed to do (I understand what it's supposed to do, I just can't put together the pieces):
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
ROLES
is an array specified in the link. I'm assuming roles
is also an array.
- Why have a setter method and a regular method with the same name?
- What array serves as the object of the
map
method? Ifroles
is['author', 'editor']
andROLES
is['author', 'editor', 'manager']
, how does the&
operator create an array formap
? - What is
2**ROLES
? I figured out that this is really just2
raised to the power ofROLES.index(r)
. - "Bitmask attributes on a Rails application" says that
(roles & ROLES)
is sanitizing the parametersroles
against the arrayROLES
, but what does sanitizing it mean? - If
r
is the current value of the array(roles & ROLES)
, how does theindex
method of2**ROLES
returnr
? I figured out that this is returning the position ofroles
in the arrayROLES
, but I still don't know how(roles & ROLES).map
interacts/works with this. - How does the
inject
method work on the condition in the brackets for themap
method?
I'd like to figure out how this bitmasking works, but I have no idea how what's on the right side of the equation for def roles=(roles)
returns an integer.