diff --git a/README.md b/README.md index d73d3f2..8078769 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,15 @@ def admin_list end ``` +`authorize` returns the object passed to it, so you can chain it like this: + +Controller: +```ruby +def show + @user = authorize User.find(params[:id]) +end +``` + You can easily get a hold of an instance of the policy through the `policy` method in both the view and controller. This is especially useful for conditionally showing links or buttons in the view: diff --git a/lib/pundit.rb b/lib/pundit.rb index ca02d5a..559b8a6 100644 --- a/lib/pundit.rb +++ b/lib/pundit.rb @@ -17,7 +17,7 @@ module Pundit # @api private class Error < StandardError; end - # Error that will be raiser when authorization has failed + # Error that will be raised when authorization has failed class NotAuthorizedError < Error attr_reader :query, :record, :policy @@ -58,7 +58,7 @@ module Pundit # @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?`) # @raise [NotAuthorizedError] if the given query method returned false - # @return [true] Always returns true + # @return [Object] Always returns the passed object record def authorize(user, record, query) policy = policy!(user, record) @@ -66,7 +66,7 @@ module Pundit raise NotAuthorizedError, query: query, record: record, policy: policy end - true + record end # Retrieves the policy scope for the given record. @@ -174,7 +174,7 @@ protected # @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. # @raise [NotAuthorizedError] if the given query method returned false - # @return [true] Always returns true + # @return [Object] Always returns the passed object record def authorize(record, query = nil) query ||= params[:action].to_s + "?" @@ -186,7 +186,7 @@ protected raise NotAuthorizedError, query: query, record: record, policy: policy end - true + record end # Allow this action not to perform authorization. diff --git a/spec/pundit_spec.rb b/spec/pundit_spec.rb index 6f0db49..0b752ad 100644 --- a/spec/pundit_spec.rb +++ b/spec/pundit_spec.rb @@ -334,6 +334,10 @@ describe Pundit do expect(controller.authorize(post)).to be_truthy end + it "returns the record on successful authorization" do + expect(controller.authorize(post)).to be(post) + end + it "can be given a different permission to check" do expect(controller.authorize(post, :show?)).to be_truthy expect { controller.authorize(post, :destroy?) }.to raise_error(Pundit::NotAuthorizedError)