Skip to content

Instantly share code, notes, and snippets.

@nickpellant
Created May 10, 2012 10:00
Show Gist options
  • Save nickpellant/2652244 to your computer and use it in GitHub Desktop.
Save nickpellant/2652244 to your computer and use it in GitHub Desktop.
Roles in Rails
class User < ActiveRecord::Base
ROLES = [:admin, :basic]
scope :with_role, -> role { where("roles_mask & #{2**User::ROLES.index(role)} > 0") }
# Checks whether the roles passed in list are set for the instance.
# @param [Array<Symbol>] roles The list of role symbols to check.
def role?(*roles)
self.roles.any? { |role| roles.include? role }
end
# Returns list of roles for the User.
# @return [Array] The lost of role symbols currently set.
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
# Converts roles to their equivalent roles mask and sets to the instance.
# @note Watch out for splat implementations since the great splat disaster of 2011.
# @param [Array<Symbol>] roles The list of role symbols to set.
def roles=(roles)
roles = roles.is_a?(Array) ? (roles.collect { |r| r.to_sym }) : [roles.to_sym]
raise "You can't assign a role that doesn't exist" unless roles.all? {|role| ROLES.include? role}
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment