Class: Admission::ResourceArbitration

Inherits:
Arbitration show all
Defined in:
lib/admission/resource_arbitration.rb

Defined Under Namespace

Classes: RulesBuilder

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Arbitration

#decide, #decide_per_inheritance, define_rules, #prepare_sitting, #rule_per_privilege

Constructor Details

#initialize(person, rules_index, request, scope_or_resource) ⇒ ResourceArbitration

Returns a new instance of ResourceArbitration.



3
4
5
6
7
8
9
# File 'lib/admission/resource_arbitration.rb', line 3

def initialize person, rules_index, request, scope_or_resource
  @person = person
  scope, @resource = scope_and_resource scope_or_resource
  @rules_index = rules_index[scope] || {}
  @request = request.to_sym
  @decisions = {}
end

Class Method Details

.nested_scope(resource, scope) ⇒ Object



51
52
53
54
# File 'lib/admission/resource_arbitration.rb', line 51

def self.nested_scope resource, scope
  resource = type_to_scope resource unless resource.is_a? Symbol
  "#{resource}:#{scope}".to_sym
end

.type_to_scope(type) ⇒ Object



46
47
48
49
# File 'lib/admission/resource_arbitration.rb', line 46

def self.type_to_scope type
  scope = @type_to_scope && @type_to_scope.call(type)
  scope ? scope.to_sym : :"#{type.name.downcase}s"
end

.type_to_scope_resolution(proc = nil, &block) ⇒ Object



42
43
44
# File 'lib/admission/resource_arbitration.rb', line 42

def self.type_to_scope_resolution proc=nil, &block
  @type_to_scope = proc || block
end

Instance Method Details

#make_decision(from_rules, privilege) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/admission/resource_arbitration.rb', line 11

def make_decision from_rules, privilege
  if from_rules
    decision = from_rules[privilege]
    if Proc === decision
      if decision.instance_variable_get :@resource_arbiter
        decision = @person.instance_exec @resource, @context, &decision
      else
        decision = @person.instance_exec @context, &decision
      end
    end

    unless Admission::VALID_DECISION.include? decision
      raise "invalid decision: #{decision}"
    end

    decision
  end
end

#scope_and_resource(scope_or_resource) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/admission/resource_arbitration.rb', line 30

def scope_and_resource scope_or_resource
  case scope_or_resource
    when Symbol
      [scope_or_resource]
    when Array
      resource, scope = scope_or_resource
      [self.class.nested_scope(resource.class, scope), resource]
    else
      [self.class.type_to_scope(scope_or_resource.class).to_sym, scope_or_resource]
  end
end