Created
November 23, 2016 20:53
-
-
Save Genkilabs/dc94a833b21044b3d4d760c2206cb045 to your computer and use it in GitHub Desktop.
Rolify: Remove all roles for a resource and enforce only one role per resource (singleton pattern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ApplicationRecord | |
rolify :strict => true, :before_add => :before_add_role | |
#Helper method to remove any existing role this user has for a resource | |
def remove_all_roles resource | |
# README: This syntax relies on changes on the following PR | |
# https://github.com/RolifyCommunity/rolify/pull/427 | |
# Or include the source of this directly: | |
# gem 'rolify', :git => "git://github.com/Genkilabs/rolify.git" | |
remove_role nil, resource | |
end | |
protected | |
#ensure that we only have a single role per resource | |
def before_add_role(role) | |
if role.resource | |
Rails.logger.debug "User::before_add_role: Adding the role of #{role.name} for #{role.resource_type} #{role.resource_id} to user #{id}" | |
#remove any pre-existing role this user has to the resource | |
remove_all_roles role.resource | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my solution to the problems of wanting an elegant way to remove any number of unknown roles from a known resource.
You can call it directly with the syntax
current_user.remove_role nil, some_resource
It relies on the following change to your ActiveRecord or Mongoid adapter:
Genkilabs/rolify@eb96834