Skip to content

Instantly share code, notes, and snippets.

@Genkilabs
Created November 23, 2016 20:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Genkilabs/dc94a833b21044b3d4d760c2206cb045 to your computer and use it in GitHub Desktop.
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)
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
@Genkilabs
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment