Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Merge pull request #625 from holyketzer/custom-messages" #684

Merged
merged 1 commit into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 0 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions lib/pundit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module Generators; end

# 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
Expand All @@ -31,7 +31,6 @@ def initialize(options = {})
@query = options[:query]
@record = options[:record]
@policy = options[:policy]
@reason = options[:reason]

message = options.fetch(:message) { "not allowed to #{query} this #{record.class}" }
end
Expand Down