Class: Philiprehberger::StateMachine::CallbackSet

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/state_machine/callbacks.rb

Overview

Stores and filters callbacks for state transitions.

Instance Method Summary collapse

Constructor Details

#initializeCallbackSet

Returns a new instance of CallbackSet.



14
15
16
# File 'lib/philiprehberger/state_machine/callbacks.rb', line 14

def initialize
  @callbacks = []
end

Instance Method Details

#add(type:, conditions: {}, &block) ⇒ Object

Register a callback.

Parameters:

  • type (:before, :after)
  • conditions (Hash) (defaults to: {})

    optional :from and :to state filters

  • block (Proc)


23
24
25
# File 'lib/philiprehberger/state_machine/callbacks.rb', line 23

def add(type:, conditions: {}, &block)
  @callbacks << Callback.new(type: type, block: block, conditions: conditions)
end

#execute(type:, from:, to:, context:, payload: {}) ⇒ Object

Execute all matching callbacks for the given transition.

Parameters:

  • type (:before, :after)
  • from (Symbol)

    source state

  • to (Symbol)

    target state

  • context (Object)

    the object to pass to the callback

  • payload (Hash) (defaults to: {})

    optional event payload forwarded to callbacks that accept it



34
35
36
37
38
39
40
41
42
# File 'lib/philiprehberger/state_machine/callbacks.rb', line 34

def execute(type:, from:, to:, context:, payload: {})
  matching(type: type, from: from, to: to).each do |callback|
    if [0, 1].include?(callback.block.arity)
      callback.block.call(context)
    else
      callback.block.call(context, payload)
    end
  end
end