Skip to content

Commit

Permalink
Add Administrate::Punditize methods as module methods (#2403)
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
jordan-brough committed Oct 13, 2023
1 parent 7d497cd commit 84badf2
Showing 1 changed file with 16 additions and 20 deletions.
36 changes: 16 additions & 20 deletions app/controllers/concerns/administrate/punditize.rb
Expand Up @@ -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!
Expand Down

0 comments on commit 84badf2

Please sign in to comment.