Class: MicroMachine

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

Constant Summary collapse

InvalidEvent =
Class.new(NoMethodError)
InvalidState =
Class.new(ArgumentError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) ⇒ MicroMachine

Returns a new instance of MicroMachine.



8
9
10
11
12
# File 'lib/micromachine.rb', line 8

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.



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

def state
  @state
end

#transitions_forObject (readonly)

Returns the value of attribute transitions_for.



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

def transitions_for
  @transitions_for
end

Instance Method Details

#eventsObject



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

def events
  transitions_for.keys
end

#on(key, &block) ⇒ Object



14
15
16
# File 'lib/micromachine.rb', line 14

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

#statesObject



44
45
46
# File 'lib/micromachine.rb', line 44

def states
  transitions_for.values.map(&:to_a).flatten.uniq
end

#trigger(event, payload = nil) ⇒ Object



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

def trigger(event, payload = nil)
  trigger?(event) and change(event, payload)
end

#trigger!(event, payload = nil) ⇒ Object



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

def trigger!(event, payload = nil)
  trigger(event, payload) or
    raise InvalidState.new("Event '#{event}' not valid from state '#{@state}'")
end

#trigger?(event) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



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

def trigger?(event)
  raise InvalidEvent unless transitions_for.has_key?(event)
  transitions_for[event].has_key?(state)
end

#triggerable_eventsObject



40
41
42
# File 'lib/micromachine.rb', line 40

def triggerable_events
  events.select { |event| trigger?(event) }
end

#when(event, transitions) ⇒ Object



18
19
20
# File 'lib/micromachine.rb', line 18

def when(event, transitions)
  transitions_for[event] = transitions
end