Search code examples
ruby-on-railsrubyruby-on-rails-3bitmapdeclarative-authorization

using a roles mask to find all users who have a certain role


I've been using a bitmask in a current project for keeping track of user roles, but now have a situation where I need to be able to do a find for all users who are a certain role.

I have my roles set-up like so:

  ROLES = %w[admin editor moderator contributor]

  def roles
    ROLES.reject do |r|
      ((roles_mask || 0) & 2**ROLES.index(r)).zero?
    end
  end

  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end

  def role_symbols
    roles.map(&:to_sym)
  end

I can find all users with exactly the same bit map, but not sure how to extract one particular role, in this case all users which have the roles "editor".


Solution

  • On http://railscasts.com/episodes/189-embedded-association, Ryan Bates provides a scope to search:

    named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
    

    You'll find examples there.