ruby-on-railspundit

Ruby / Pundit -> user.owner_of?


I saw below in the pundit documentation and was wondering if that is part of some ruby or pundit magic based on user_id being present in a given model. Or if it's just something they used to get a point across https://github.com/varvet/pundit

enter image description here


Solution

  • It seems to me that this is just an example of the use of a function in the user that you have to implement yourself.

    For example:

    class User < ApplicationRecord
       ...
    
       def owner_of?(resource)
          self.id == resource.user.id
       end
    
       ...
    end
    

    First condition user.admin? is usable thanks to the enum in the user class. Rails provide dynamic methods to verify the role of a particular user

    class User < ApplicationRecord
       ...
       enum role: [ 
          :admin,
          :moderator,
          :editor
       ]
       ...
    end
    

    This makes the methods available on the user object:

    user.admin?
    user.moderator?
    user.editor?