Search code examples
ruby-on-railsrolify

Create role based only on instance with Rolify


Is there an option to create roles that we can assign only to instances but not to the whole class? I want to define a role scoped to a resource instance:

user = User.find(2)
user.add_role :moderator, Forum.first

But I want to avoid defining roles scoped to a whole class:

user = User.find(3)
user.add_role :moderator, Forum

Is there any way to forbid the second choice?


Solution

  • I have no idea about what Rolify provides for that, but you always might use plain old good ruby Module#prepend for that:

    User.prepend(Module.new do
      def add_role(role, target)
        raise "Not allowed" if target.is_a?(Class)
        super(role, target)
      end
    end)