Class: CanHasState::Trigger

Inherits:
Object
  • Object
show all
Defined in:
lib/can_has_state/trigger.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(definition, from:, to:, type:, deferred: false, trigger:) ⇒ Trigger

Returns a new instance of Trigger.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/can_has_state/trigger.rb', line 7

def initialize(definition, from:, to:, type:, deferred: false, trigger:)
  @state_machine = definition
  @from          = Array(from).map{|v| v&.to_s}
  @to            = Array(to).map{|v| v&.to_s}
  @type          = type
  @deferred      = !!deferred
  @perform       = Array(trigger)

  if @deferred && !state_machine.parent_context.respond_to?(:after_save)
    raise ArgumentError, 'use of deferred triggers requires support for #after_save callbacks'
  end
  @perform.each do |m|
    unless [Proc, String, Symbol].include?(m.class)
      raise ArgumentError, "Expecing Symbol or Proc for #{@type.inspect}, got #{m.class} : #{m}"
    end
  end
end

Instance Attribute Details

#deferredObject (readonly)

Returns the value of attribute deferred.



5
6
7
# File 'lib/can_has_state/trigger.rb', line 5

def deferred
  @deferred
end

#fromObject (readonly)

Returns the value of attribute from.



5
6
7
# File 'lib/can_has_state/trigger.rb', line 5

def from
  @from
end

#performObject (readonly)

Returns the value of attribute perform.



5
6
7
# File 'lib/can_has_state/trigger.rb', line 5

def perform
  @perform
end

#state_machineObject

Returns the value of attribute state_machine.



4
5
6
# File 'lib/can_has_state/trigger.rb', line 4

def state_machine
  @state_machine
end

#toObject (readonly)

Returns the value of attribute to.



5
6
7
# File 'lib/can_has_state/trigger.rb', line 5

def to
  @to
end

#typeObject (readonly)

Returns the value of attribute type.



5
6
7
# File 'lib/can_has_state/trigger.rb', line 5

def type
  @type
end

Instance Method Details

#call(record) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/can_has_state/trigger.rb', line 31

def call(record)
  perform.each do |m|
    case m
    when Proc
      if m.arity.zero?
        record.instance_eval(&m)
      else
        m.call record
      end
    when Symbol, String
      record.send m
    end
  end
end

#matches?(from:, to:, deferred: false) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/can_has_state/trigger.rb', line 25

def matches?(from:, to:, deferred: false)
  matches_from?(from) &&
    matches_to?(to) &&
    matches_deferred?(deferred)
end