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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't even see that. Thank you for pointing it out.