Class: TinyStateMachine::Machine
- Inherits:
-
Object
- Object
- TinyStateMachine::Machine
- Defined in:
- lib/tiny_state_machine.rb
Overview
A tiny state machine
Instance Attribute Summary collapse
-
#state ⇒ String or Symbol
readonly
Current state of the state machine.
Instance Method Summary collapse
-
#event(event, hash) ⇒ Object
declare events you can use :any in the hash key for an event that can come from any state.
-
#initialize(initial_state) {|self| ... } ⇒ Machine
constructor
Construct a tiny state machine with an initial state.
-
#on_state_change(&block) ⇒ Object
register a listener to a state change.
-
#trigger(event) ⇒ Object
trigger an event.
Constructor Details
#initialize(initial_state) {|self| ... } ⇒ Machine
Construct a tiny state machine with an initial state.
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
#state ⇒ String or Symbol (readonly)
Returns 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
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.
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
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 |