From 84badf2515db578b79555caec5df44f3be59e2aa Mon Sep 17 00:00:00 2001 From: Jordan Brough Date: Fri, 13 Oct 2023 07:47:49 -0600 Subject: [PATCH] Add Administrate::Punditize methods as module methods (#2403) Instead of adding them via `included do`. If they are added via "included do" it makes it hard to override the method in an app's controller. Example: ```ruby module Admin class ApplicationController < Administrate::ApplicationController include Administrate::Punditize def scoped_resource super.where(archived: false) end end end ``` That example will skip pundit completely, because the `def scoped_resource` from `Administrate::Punditize` was added via `included do`, which means it will behave as if we had defined the method twice in `Admin ::ApplicationController`, which will result in the first definition from `Administrate::Punditize` being ignored. And "super" will refer to the no-op definition provided in the base class `Administrate::ApplicationController`. This seems unexpected to me, and makes it hard to add functionality that layers on to pof what `Administrate::Punditize` does. However, if we defined `def scoped_resource` as a module method in `Administrate::Punditize` then `super` in `Admin::ApplicationController` will refer to the method defined in `Administrate::Punditize`. --- .../concerns/administrate/punditize.rb | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/app/controllers/concerns/administrate/punditize.rb b/app/controllers/concerns/administrate/punditize.rb index 41c81ef03..9a3841985 100644 --- a/app/controllers/concerns/administrate/punditize.rb +++ b/app/controllers/concerns/administrate/punditize.rb @@ -9,31 +9,27 @@ module Punditize include Pundit end - included do - private - - def policy_namespace - [] - end + private - def scoped_resource - namespaced_scope = policy_namespace + [super] - policy_scope!(pundit_user, namespaced_scope) - end + def policy_namespace + [] + end - def authorize_resource(resource) - namespaced_resource = policy_namespace + [resource] - authorize namespaced_resource - end + def scoped_resource + namespaced_scope = policy_namespace + [super] + policy_scope!(pundit_user, namespaced_scope) + end - def authorized_action?(resource, action) - namespaced_resource = policy_namespace + [resource] - policy = Pundit.policy!(pundit_user, namespaced_resource) - policy.send("#{action}?".to_sym) - end + def authorize_resource(resource) + namespaced_resource = policy_namespace + [resource] + authorize namespaced_resource end - private + def authorized_action?(resource, action) + namespaced_resource = policy_namespace + [resource] + policy = Pundit.policy!(pundit_user, namespaced_resource) + policy.send("#{action}?".to_sym) + end def policy_scope!(user, scope) policy_scope_class = Pundit::PolicyFinder.new(scope).scope!