Finally getting to use Pundit after hearing about it for years!
I'd love to know the best practice for ensuring that all actions within, say an admin namespace, are protected by an AdminPolicy. I have users that are admins, and I want them to be able to do anything and everything on controller actions within said namespace.
I currently have a AdminController super class which contains
class Admin::AdminController < ApplicationController
before_action :check_if_admin
def check_if_admin
authorize :admin
end
end
and an AdminPolicy which is
class AdminPolicy
attr_reader :current_user
def initialize(current_user, _)
@current_user = current_user
end
def method_missing(name, *args)
current_user.roles.include? "admin"
end
end
Using method_missing works in this case, but I'm one of those that prefers not to use where possible. Is the recommendation to just be careful about listing out every single controller action for every action with my Admin namespace? Or does this method_missing strategy work in practice?
I've seen some answers about this question (https://github.com/elabs/pundit/issues/320, https://stackoverflow.com/questions/45768490/do-i-have-to-define-all-methods-in-pundit-policy) but I'd love to know if there's an 'official' recommendation. Happy to contribute said recommendation into the Pundit wiki afterwards.
authorize(:admin, :admin?) in your controller eliminates the need for method_missing in your policy and allows your policy to provide just one method (admin?) to authorize admins.
What @ce07c3 suggests sounds reasonable to me.
Most helpful comment
authorize(:admin, :admin?)in your controller eliminates the need formethod_missingin your policy and allows your policy to provide just one method (admin?) to authorize admins.