lib/critic/policy.rb in critic-0.1.1 vs lib/critic/policy.rb in critic-0.2.0
- old
+ new
@@ -23,45 +23,29 @@
policies.fetch(resource_class) { "#{resource_class}Policy".constantize }
end
included do
- include ActiveSupport::Callbacks
-
- if ActiveSupport::VERSION::MAJOR < 4
- define_callbacks :authorize, terminator: 'authorization.result == false || result == false'
- else
- define_callbacks :authorize, terminator: ->(target, result) { target.authorization.result == false || false == result }
- end
+ include Critic::Callbacks
end
# Policy entry points
module ClassMethods
- def authorize(action, subject, resource, args=nil)
+ def authorize(action, subject, resource, args = nil)
new(subject, resource).authorize(action, *args)
end
def scope(action = nil)
action.nil? ? (@scope || :index) : (@scope = action)
end
-
- def before_authorize(*args, **options, &block)
- set_callback(:authorize, :before, *args, **options, &block)
- end
-
- def after_authorize(*args, **options, &block)
- set_callback(:authorize, :after, *args, **options, &block)
- end
-
- def around_authorize(*args, **options, &block)
- set_callback(:authorize, :around, *args, **options, &block)
- end
end
attr_reader :subject, :resource, :errors
attr_accessor :authorization
+ delegate :messages, :metadata, to: :authorization
+
def initialize(subject, resource)
@subject = subject
@resource = resource
@errors = []
end
@@ -71,19 +55,13 @@
end
def authorize(action, *args)
self.authorization = Critic::Authorization.new(self, action)
- result = false
+ result = catch(:halt) { process_authorization(action, args) }
- begin
- run_callbacks(:authorize) { result = public_send(action, *args) }
- rescue Critic::AuthorizationDenied
- authorization.granted = false
- ensure
- authorization.result = result if authorization.result.nil?
- end
+ authorization.result = result if authorization.result.nil?
case authorization.result
when Critic::Authorization
# user has accessed authorization directly
when String
@@ -95,7 +73,19 @@
else
authorization.granted = true
end
authorization
+ end
+
+ protected
+
+ def halt(*response)
+ throw :halt, *response
+ end
+
+ private
+
+ def process_authorization(action, args)
+ public_send(action, *args)
end
end