Class: MicroMachine

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) ⇒ MicroMachine

Returns a new instance of MicroMachine.



5
6
7
8
9
# File 'lib/micromachine.rb', line 5

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.



3
4
5
# File 'lib/micromachine.rb', line 3

def state
  @state
end

#transitions_forObject (readonly)

Returns the value of attribute transitions_for.



2
3
4
# File 'lib/micromachine.rb', line 2

def transitions_for
  @transitions_for
end

Instance Method Details

#on(key, &block) ⇒ Object



11
12
13
# File 'lib/micromachine.rb', line 11

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

#trigger(event) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/micromachine.rb', line 15

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