Class: ComposableStateMachine::Behaviors

Inherits:
Object
  • Object
show all
Defined in:
lib/composable_state_machine/behaviors.rb

Overview

Defines the behaviors of a state machine.

Instance Method Summary collapse

Constructor Details

#initialize(behaviors = {}, callbacks_factory = Callbacks) ⇒ Behaviors

Parameters:

  • behaviors (Hash<behavior, Hash<trigger, callback>>) (defaults to: {})

    triggers and callbacks per behavior. The triggers and callbacks can be provided as an object the responds to #call or they can be provided as a Hash<trigger, callback>. In the latter case, the callbacks factory will be used to create an object that would manage the callbacks for the behavior.

  • callbacks_factory (Object) (defaults to: Callbacks)

    object whose #new method will be called with a Hash<trigger, callback>.



9
10
11
12
13
14
15
16
# File 'lib/composable_state_machine/behaviors.rb', line 9

def initialize(behaviors = {}, callbacks_factory = Callbacks)
  @callbacks_factory = callbacks_factory
  @behaviors = behaviors.reduce({}) do |memo, (behavior, value)|
    handler = value.respond_to?(:call) ? value : @callbacks_factory.new(value)
    memo[behavior] = handler
    memo
  end
end

Instance Method Details

#call(runner, behavior, *args) ⇒ self

Runs callbacks for a behavior with a runner.

Selects the callback manager for the behavior and forwards to its #call method.

Parameters:

  • runner (Object)

    the runner

  • behavior (Object)

    the behavior

  • args (Array<Object>)

    parameters to pass to the callback manager’s #call method.

Returns:

  • (self)

    for chaining



40
41
42
43
44
45
# File 'lib/composable_state_machine/behaviors.rb', line 40

def call(runner, behavior, *args)
  @behaviors[behavior].tap do |handler|
    handler.call(runner, *args) if handler
  end
  self
end

#on(behavior, *args, &block) ⇒ self

Adds callbacks for a behavior.

Selects the callback manager for the behavior and forwards to its #on method.

Parameters:

  • behavior (Object)

    the behavior

  • args (Array<Object>)

    parameters to pass to the callback manager’s #on method.

Returns:

  • (self)

    for chaining



26
27
28
29
# File 'lib/composable_state_machine/behaviors.rb', line 26

def on(behavior, *args, &block)
  (@behaviors[behavior] ||= @callbacks_factory.new).on(*args, &block)
  self
end