Class: ComposableStateMachine::MachineWithExternalState

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

Overview

State machine instance that manages its state via a reader and writer objects.

Direct Known Subclasses

Machine

Instance Method Summary collapse

Constructor Details

#initialize(model, state_reader, state_writer, options = {}) ⇒ MachineWithExternalState

Creates an instance.

Parameters:

  • model (Model, ...)

    the model for the machine

  • state_reader (Proc, Method, ...)

    object whose #call method will return the current state

  • state_writer (Proc, Method, ...)

    object whose #call method will be called with the new state after a transition

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

    the options to create the machine with.

Options Hash (options):

  • :state (Object) — default: model#initial_state

    State of the machine.

  • :callback_runner (Object) — default: model#callback_runner

    Object whose #run_state_machine_callback method will be used to execute behavior callbacks.



13
14
15
16
17
18
19
20
# File 'lib/composable_state_machine/machine_with_external_state.rb', line 13

def initialize(model, state_reader, state_writer, options = {})
  @model = model
  @state_reader = state_reader
  @state_writer = state_writer
  @callback_runner = options[:callback_runner] || model.callback_runner
  initial_state = options[:state] || model.initial_state
  @state_writer.call(initial_state)
end

Instance Method Details

#==(other_state) ⇒ TrueClass, FalseClass

Checks whether the state of the machine is equal to another state

Returns:

  • (TrueClass, FalseClass)


36
37
38
# File 'lib/composable_state_machine/machine_with_external_state.rb', line 36

def ==(other_state)
  @state_reader.call == other_state
end

#trigger(event, *args) ⇒ Object?

Executes the transition and behaviors associated with an event.

Parameters:

  • event (Object)

    the event

  • args (Array<Object>)

    event arguments

Returns:

  • (Object, nil)

    the result of model#transition



28
29
30
31
# File 'lib/composable_state_machine/machine_with_external_state.rb', line 28

def trigger(event, *args)
  current_state = @state_reader.call
  @model.transition(current_state, event, args, @callback_runner, &@state_writer)
end