Cancancan - lookup permissions by string

218 Views Asked by At

I've used cancancan a lot for checking permissions on specific classes/instances.

class Ability
  include CanCan::Ability

  def initialize(user)  
    can do |action, subject_class|
      # Lookup users permission inside of this block.
      # action might be :read
      # subject_class might be a class like Company.
    end
  end
end

Above example would for work for user.can?(:read, Company).

I've now created a permission set for multiple classes. My app has multiple settings that I wanted to group under AccountingSetting so that I can check the permission via user.can?(:read, "AccountingSetting"). Since AccountingSetting is not an actual model/class I pass a string to the method. This does not work since the subject_class argument returns String-class instead of the actual string.

Is a string lookup for permissions not supported by cancancan or am I missing something?

1

There are 1 best solutions below

0
ChrisK On

Digged through the docs a bit more and found a solution:

https://rdoc.info/github/CanCanCommunity/cancancan/CanCan/Ability#can-instance_method

The can block returns a third argument, that will include the value of all none class parameters.

  def initialize(user)  
    can do |action, class, object|
      # Lookup users permission inside of this block.
      # action might be :read
      # class might be a class like Company
      # object might be nil or a string/symbol.
    end
  end

So when can?(:read, 'AnythingPossibleThingy') is called, the object argument is populated with 'AnythingPossibleThingy' which I can use to lookup the permissions.