Class: TinyStateMachine::Machine

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

Overview

A tiny state machine

Examples:

sm = TinyStateMachine::Machine.new :in_store do |sm|
  sm.event :buy, :in_store => :new
  sm.event :use, :new => :used
  sm.event :use, :used => :used
  sm.event :break, :used => :broken
  sm.event :fix, :broken => :used
  sm.on_state_change do |event, from_state, to_state|
    puts "new state = #{to_state}"
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) {|self| ... } ⇒ Machine

Construct a tiny state machine with an initial state.

Parameters:

  • initial_state (String or Symbol)

    state the machine is in after initialization

Yields:

  • (self)

    yields the machine for easy definition of states

Yield Parameters:



30
31
32
33
34
35
36
37
# File 'lib/tiny_state_machine.rb', line 30

def initialize(initial_state)
  @state = initial_state
  @events = Array.new
  @callback_block = nil
  if block_given?
    yield self
  end
end

Instance Attribute Details

#stateString or Symbol (readonly)

Returns current state of the state machine.

Returns:

  • (String or Symbol)

    current state of the state machine.



23
24
25
# File 'lib/tiny_state_machine.rb', line 23

def state
  @state
end

Instance Method Details

#event(event, hash) ⇒ Object

declare events you can use :any in the hash key for an event that can come from any state

Examples:

sm.event :error, :any => :error

Parameters:

  • event (String or Symbol)

    state name

  • hash (Hash)

    a Hash in the form : old_state => new_state



46
47
48
49
50
# File 'lib/tiny_state_machine.rb', line 46

def event(event, hash)
  hash.each do |from, to|
    @events << { event: event, from: from, to: to }
  end
end

#on_state_change(&block) ⇒ Object

register a listener to a state change.

Parameters:

  • block (Proc)

    block that will be triggered



72
73
74
# File 'lib/tiny_state_machine.rb', line 72

def on_state_change(&block)
  @callback_block = block
end

#trigger(event) ⇒ Object

trigger an event. It will return the new state the machine is in and call the listener’s block

Parameters:

  • event (String or Symbol)

    event to trigger

Returns:

  • the new state the machine is in

Raises:

  • (InvalidEvent)

    if the event is invalid (incorrect state)

See Also:



60
61
62
63
64
65
66
67
# File 'lib/tiny_state_machine.rb', line 60

def trigger(event)
  e = @events.find { |e| e[:event] == event && (e[:from] == @state || e[:from] == :any) }
  raise InvalidEvent, "Invalid event '#{event}' from state '#{@state}'" if e.nil?
  old_state = @state
  @state = e[:to]
  @callback_block.call(event, old_state, @state) if @callback_block
  @state
end