Last active
July 2, 2020 15:50
-
-
Save coderliu/df69abc96cc0bc5098edb2ca4cab0651 to your computer and use it in GitHub Desktop.
Rails controller concerns for using pundit with scope of controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/concerns/scoped_policies | |
# add `include ScopedPolicies` to your scoped base controller such as Api::BaseController | |
module ScopedPolicies | |
extend ActiveSupport::Concern | |
included do | |
helper_method :authorize | |
helper_method :policy_scope | |
end | |
# These are workarounds for the lack of support for namespacing in pundit | |
# https://github.com/elabs/pundit/issues/12 | |
def controller_namespace | |
@controller_namespace ||= self.class.to_s.sub(/::[A-z]*Controller/, '') | |
end | |
def authorize(record, query = nil) | |
klass = "#{controller_namespace}::#{record.model_name}Policy".constantize | |
policy = klass.new(current_user, record) | |
query ||= "#{params[:action]}?" | |
@_policy_authorized = true | |
unless policy.public_send(query) | |
error = Pundit::NotAuthorizedError.new("not allowed to #{query} this #{record}") | |
error.query, error.record, error.policy = query, record, policy | |
raise error | |
end | |
true | |
end | |
def policy_scope(scope) | |
klass = "#{controller_namespace}::#{scope.model_name}Policy::Scope".constantize | |
policy = klass.new(current_user, scope) | |
@_policy_scoped = true | |
policy.resolve | |
end | |
end |
I think lines
22
and37
need updating accordingly to work with the latest version of pundit, based on what I've found here:# line 22 @_pundit_policy_authorized = true
# line 37 @_pundit_policy_scoped = true
You are right. This gist is a little bit outdated.
According to the newest documentation of Pundit, I think you should not need to use the strategy described in this gist anymore.
I didn't even see that. Thank you for pointing it out.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think lines
22
and37
need updating accordingly to work with the latest version of pundit, based on what I've found here: