Class: MicroMachine
- Inherits:
-
Object
- Object
- MicroMachine
- Defined in:
- lib/micromachine.rb
Constant Summary collapse
- InvalidEvent =
Class.new(NoMethodError)
- InvalidState =
Class.new(ArgumentError)
Instance Attribute Summary collapse
-
#state ⇒ Object
readonly
Returns the value of attribute state.
-
#transitions_for ⇒ Object
readonly
Returns the value of attribute transitions_for.
Instance Method Summary collapse
- #events ⇒ Object
-
#initialize(initial_state) ⇒ MicroMachine
constructor
A new instance of MicroMachine.
- #on(key, &block) ⇒ Object
- #states ⇒ Object
- #trigger(event, payload = nil) ⇒ Object
- #trigger!(event, payload = nil) ⇒ Object
- #trigger?(event) ⇒ Boolean
- #triggerable_events ⇒ Object
- #when(event, transitions) ⇒ Object
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
#state ⇒ Object (readonly)
Returns the value of attribute state.
6 7 8 |
# File 'lib/micromachine.rb', line 6 def state @state end |
#transitions_for ⇒ Object (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
#events ⇒ Object
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 |
#states ⇒ Object
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
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_events ⇒ Object
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 |