From b0fd39777518940a23668c55a84e3c4f524bfc4f Mon Sep 17 00:00:00 2001 From: Kim Burgestrand Date: Tue, 10 Aug 2021 10:28:31 +0200 Subject: [PATCH] Revert "Merge pull request #625 from holyketzer/custom-messages" This reverts commit 6be4621538f916124f76b57460c8cc46597a3b6a, reversing changes made to 872ed6872931b6504778d0e5fab927e67fb66bb1. Reverting this because it's blocking us from making a new release, see: https://github.com/varvet/pundit/issues/656#issuecomment-895827605 --- README.md | 40 ---------------------------------------- lib/pundit.rb | 3 +-- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/README.md b/README.md index e19e77a..1bdea7c 100644 --- a/README.md +++ b/README.md @@ -544,46 +544,6 @@ en: Of course, this is just an example. Pundit is agnostic as to how you implement your error messaging. -## Multiple error messages per one policy action - -If there are multiple reasons that authorization can be denied, you can show different messages by raising exceptions in your policy: - -In your policy class raise `Pundit::NotAuthorizedError` with custom error message or I18n key in `reason` argument: - -```ruby -class ProjectPolicy < ApplicationPolicy - def create? - if user.has_paid_subscription? - if user.project_limit_reached? - raise Pundit::NotAuthorizedError, reason: 'user.project_limit_reached' - else - true - end - else - raise Pundit::NotAuthorizedError, reason: 'user.paid_subscription_required' - end - end -end -``` - -Then you can get this error message in exception handler: -```ruby -rescue_from Pundit::NotAuthorizedError do |e| - message = e.reason ? I18n.t("pundit.errors.#{e.reason}") : e.message - flash[:error] = message, scope: "pundit", default: :default - redirect_to(request.referrer || root_path) -end -``` - -```yaml -en: - pundit: - errors: - user: - paid_subscription_required: 'Paid subscription is required' - project_limit_reached: 'Project limit is reached' -``` - ## Manually retrieving policies and scopes Sometimes you want to retrieve a policy for a record outside the controller or diff --git a/lib/pundit.rb b/lib/pundit.rb index 0b3e31a..c3a1d1d 100644 --- a/lib/pundit.rb +++ b/lib/pundit.rb @@ -22,7 +22,7 @@ module Pundit # Error that will be raised when authorization has failed class NotAuthorizedError < Error - attr_reader :query, :record, :policy, :reason + attr_reader :query, :record, :policy def initialize(options = {}) if options.is_a? String @@ -31,7 +31,6 @@ module Pundit @query = options[:query] @record = options[:record] @policy = options[:policy] - @reason = options[:reason] message = options.fetch(:message) { "not allowed to #{query} this #{record.class}" } end