Module: Warren::Helpers::StateMachine

Included in:
Client, Fox
Defined in:
lib/warren/helpers/state_machine.rb

Overview

Provides an incredibly simple state machine. It merely lets you define states with #state which defines two methods ‘#state!` to transition into the state and `#state?` to query if we are in the state.

Usage:

Examples:

Basic usage

class Machine
  extend Warren::Helpers::StateMachine
  states :started, :started
end

machine = Machine.new
machine.started!
machine.started? # => true
machine.stopped? # => false
machine.stopped!
machine.started? # => false
machine.stopped? # => stopped

Instance Method Summary collapse

Instance Method Details

#state(state_name) ⇒ Void

Define a new state, generates two methods ‘#state!` to transition into the state and `#state?` to query if we are in the state.

Parameters:

  • state_name (Symbol, String)

    The name of the state

Returns:

  • (Void)


35
36
37
38
# File 'lib/warren/helpers/state_machine.rb', line 35

def state(state_name)
  define_method(:"#{state_name}!") { @state = state_name }
  define_method(:"#{state_name}?") { @state == state_name }
end

#push2(state_name, ...) ⇒ Void

Define new states, generates two methods for each state ‘#state!` to transition into the state and `#state?` to query if we are in the state.

Parameters:

  • state_name (Symbol, String)

    The name of the state

  • ... (Symbol, String)

    More states

Returns:

  • (Void)


50
51
52
# File 'lib/warren/helpers/state_machine.rb', line 50

def states(*state_names)
  state_names.each { |state_name| state(state_name) }
end