Module: Critic::Policy

Extended by:
ActiveSupport::Concern
Defined in:
lib/critic/policy.rb

Overview

Represents the authorization policy interface

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#authorizationObject

Returns the value of attribute authorization.



72
73
74
# File 'lib/critic/policy.rb', line 72

def authorization
  @authorization
end

Class Method Details

.for(resource) ⇒ Object



22
23
24
25
26
# File 'lib/critic/policy.rb', line 22

def self.for(resource)
  resource_class = resource_class_for(resource)

  policies.fetch(resource_class) { "#{resource_class}Policy".constantize }
end

.policiesObject



6
7
8
# File 'lib/critic/policy.rb', line 6

def self.policies
  @_policies ||= Hash.new { |h, k| h[k.to_s] = nil }
end

.resource_class_for(object) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/critic/policy.rb', line 11

def self.resource_class_for(object)
  if object.respond_to?(:model_name)
    # used for pulling class out of ActiveRecord::Relation objects
    object.model_name
  elsif object.is_a?(Class)
    object.to_s.demodulize
  else
    object.class.to_s.demodulize
  end
end

Instance Method Details

#authorize(action, *args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/critic/policy.rb', line 49

def authorize(action, *args)
  self.authorization = Critic::Authorization.new(self, action)

  result = catch(:halt) { process_authorization(action, args) }

  authorization.result = result if authorization.result.nil?

  case authorization.result
  # when Critic::Authorization
  #   # user has accessed authorization directly
  when String
    authorization.granted = false
    authorization.messages << result
  when nil, false
    authorization.granted = false
    authorization.messages << failure_message(action)
  else
    authorization.granted = true
  end

  authorization
end

#initialize(subject, resource) ⇒ Object



43
44
45
46
47
# File 'lib/critic/policy.rb', line 43

def initialize(subject, resource)
  @subject = subject
  @resource = resource
  @errors = []
end