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

Don't look for NilClassPolicy

Fixes #251

Contains little refactoring, to avoid duplication in setting error.
This commit is contained in:
Michał Darda 2015-02-25 20:30:08 +01:00
parent ce62bc5cd1
commit f898595154
2 changed files with 32 additions and 5 deletions

View file

@ -8,7 +8,17 @@ require "active_support/dependencies/autoload"
module Pundit
class NotAuthorizedError < StandardError
attr_accessor :query, :record, :policy
attr_reader :query, :record, :policy
def initialize(options = {})
@query = options[:query]
@record = options[:record]
@policy = options[:policy]
message = options.fetch(:message) { "not allowed to #{query} this #{record}" }
super(message)
end
end
class AuthorizationNotPerformedError < StandardError; end
class PolicyScopingNotPerformedError < AuthorizationNotPerformedError; end
@ -64,14 +74,19 @@ module Pundit
def authorize(record, query=nil)
query ||= params[:action].to_s + "?"
if record.blank?
raise NotAuthorizedError.new(
message: "cannot #{query} a blank object",
query: query
)
end
@_pundit_policy_authorized = true
policy = policy(record)
unless policy.public_send(query)
error = NotAuthorizedError.new("not allowed to #{query} this #{record}")
error.query, error.record, error.policy = query, record, policy
raise error
raise NotAuthorizedError.new(query: query, record: record, policy: policy)
end
true

View file

@ -191,6 +191,18 @@ describe Pundit do
expect(error.policy).to eq controller.policy(post)
end
end
it "raises an error when receives nil and never look for policy" do
expect(controller).to receive(:policy).with(nil).never
expect { controller.authorize(nil, :destroy?) }.to raise_error do |error|
expect(error).to be_kind_of(Pundit::NotAuthorizedError)
expect(error.query).to eq :destroy?
expect(error.message).to eq "cannot destroy? a blank object"
end
end
end
describe "#pundit_user" do