class MicroFSM
Constants
- InvalidEvent
- InvalidState
- InvalidTransition
- VERSION
Attributes
state[RW]
Public Class Methods
new(initial_state)
click to toggle source
# File lib/microfsm.rb, line 10 def initialize(initial_state) @state = initial_state @transitions_for = {} @callbacks_for = {} end
Public Instance Methods
events()
click to toggle source
# File lib/microfsm.rb, line 46 def events @transitions_for.keys.sort end
states()
click to toggle source
# File lib/microfsm.rb, line 54 def states @transitions_for.values.map(&:to_a).flatten.uniq.sort end
trigger(event)
click to toggle source
# File lib/microfsm.rb, line 31 def trigger(event) trigger?(event) and transit(event) end
trigger!(event)
click to toggle source
# File lib/microfsm.rb, line 35 def trigger!(event) trigger(event) or raise InvalidState.new(msg(event)) end
trigger?(event)
click to toggle source
# File lib/microfsm.rb, line 40 def trigger?(event) raise InvalidEvent.new(msg(event)) unless @transitions_for.has_key?(event) @transitions_for[event].has_key?(state) end
triggerable_events()
click to toggle source
# File lib/microfsm.rb, line 50 def triggerable_events events.select { |event| trigger?(event) }.sort end
when(event, transitions, &block)
click to toggle source
# File lib/microfsm.rb, line 16 def when(event, transitions, &block) @transitions_for[event] ||= {} @callbacks_for[event] ||= {} transitions.each do |from, to| nto = @transitions_for[event][from] raise InvalidTransition if nto && nto != to @transitions_for[event][from] = to @callbacks_for[event][from] ||= [] @callbacks_for[event][from] << block if block end self end
Private Instance Methods
msg(event)
click to toggle source
# File lib/microfsm.rb, line 66 def msg(event) "State: #{@state}; Event: #{event}" end
transit(event)
click to toggle source
# File lib/microfsm.rb, line 59 def transit(event) callbacks = @callbacks_for[event][@state] @state = @transitions_for[event][@state] callbacks.each { |callback| callback.call(event) } true end