1
0
Fork 0
mirror of https://github.com/varvet/pundit.git synced 2022-11-09 12:30:11 -05:00

Allow overriding policy class on authorize method

This commit is contained in:
Pablo Crivella 2016-12-19 11:54:01 +01:00
parent 7f4a5d42eb
commit 2c80766b51
4 changed files with 31 additions and 2 deletions

View file

@ -133,6 +133,18 @@ def publish
end
```
You can pass an argument to override the policy class if necessary. For example:
```ruby
def create
@publication = find_publication # assume this method returns any model that behaves like a publication
# @publication.class => Post
authorize @publication, policy_class: PublicationPolicy
@publication.publish!
redirect_to @publication
end
```
If you don't have an instance for the first argument to `authorize`, then you can pass
the class. For example:

View file

@ -189,14 +189,15 @@ protected
# @param record [Object] the object we're checking permissions of
# @param query [Symbol, String] the predicate method to check on the policy (e.g. `:show?`).
# If omitted then this defaults to the Rails controller action name.
# @param policy_class [Class] the policy class we wan't to force use of
# @raise [NotAuthorizedError] if the given query method returned false
# @return [Object] Always returns the passed object record
def authorize(record, query = nil)
def authorize(record, query = nil, policy_class: nil)
query ||= "#{action_name}?"
@_pundit_policy_authorized = true
policy = policy(record)
policy = policy_class ? policy_class.new(pundit_user, record) : policy(record)
raise NotAuthorizedError, query: query, record: record, policy: policy unless policy.public_send(query)

View file

@ -375,6 +375,10 @@ describe Pundit do
expect { controller.authorize(post, :destroy?) }.to raise_error(Pundit::NotAuthorizedError)
end
it "can be given a different policy class" do
expect(controller.authorize(post, :create?, policy_class: PublicationPolicy)).to be_truthy
end
it "works with anonymous class policies" do
expect(controller.authorize(article_tag, :show?)).to be_truthy
expect { controller.authorize(article_tag, :destroy?) }.to raise_error(Pundit::NotAuthorizedError)

View file

@ -91,6 +91,18 @@ class CommentPolicy < Struct.new(:user, :comment)
end
end
class PublicationPolicy < Struct.new(:user, :publication)
class Scope < Struct.new(:user, :scope)
def resolve
scope
end
end
def create?
true
end
end
class Comment
extend ActiveModel::Naming
end