Class: MicroMachine

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

Overview

Finite State Machine

Usage:

machine = MicroMachine.new(:new) # Initial state.

machine.transitions_for[:confirm] = { :new => :confirmed }
machine.transitions_for[:ignore]  = { :new => :ignored }
machine.transitions_for[:reset]   = { :confirmed => :new, :ignored => :new }

machine.trigger(:confirm)  #=> true
machine.trigger(:ignore)   #=> false
machine.trigger(:reset)    #=> true
machine.trigger(:ignore)   #=> true

It also handles callbacks that are executed when entering a different state.

machine.on(:confirmed) do
  puts "Confirmed"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) ⇒ MicroMachine



25
26
27
28
29
# File 'lib/micromachine.rb', line 25

def initialize initial_state
  @state = initial_state
  @transitions_for = Hash.new
  @callbacks = Hash.new { |hash, key| hash[key] = [] }
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



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

def state
  @state
end

#transitions_forObject (readonly)

Returns the value of attribute transitions_for.



22
23
24
# File 'lib/micromachine.rb', line 22

def transitions_for
  @transitions_for
end

Instance Method Details

#on(key, &block) ⇒ Object



31
32
33
# File 'lib/micromachine.rb', line 31

def on key, &block
  @callbacks[key] << block
end

#trigger(event) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/micromachine.rb', line 35

def trigger event
  if transitions_for[event][@state]
    @state = transitions_for[event][@state]
    @callbacks[@state].each { |callback| callback.call }
    true
  end
end