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
- #==(some_state) ⇒ Object
- #events ⇒ Object
-
#initialize(initial_state) ⇒ MicroMachine
constructor
A new instance of MicroMachine.
- #on(key, &block) ⇒ Object
- #states ⇒ Object
- #trigger(event) ⇒ Object
- #trigger!(event) ⇒ Object
- #trigger?(event) ⇒ Boolean
- #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
#==(some_state) ⇒ Object
54 55 56 |
# File 'lib/micromachine.rb', line 54 def ==(some_state) state == some_state end |
#events ⇒ Object
46 47 48 |
# File 'lib/micromachine.rb', line 46 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
50 51 52 |
# File 'lib/micromachine.rb', line 50 def states events.map { |e| transitions_for[e].to_a }.flatten.uniq end |
#trigger(event) ⇒ Object
22 23 24 25 26 27 28 29 30 31 |
# File 'lib/micromachine.rb', line 22 def trigger(event) if trigger?(event) @state = transitions_for[event][@state] callbacks = @callbacks[@state] + @callbacks[:any] callbacks.each { |callback| callback.call(event) } true else false end end |
#trigger!(event) ⇒ Object
33 34 35 36 37 38 39 |
# File 'lib/micromachine.rb', line 33 def trigger!(event) if trigger(event) true else raise InvalidState.new("Event '#{event}' not valid from state '#{@state}'") end end |
#trigger?(event) ⇒ Boolean
41 42 43 44 |
# File 'lib/micromachine.rb', line 41 def trigger?(event) raise InvalidEvent unless transitions_for.has_key?(event) transitions_for[event][state] ? true : false end |
#when(event, transitions) ⇒ Object
18 19 20 |
# File 'lib/micromachine.rb', line 18 def when(event, transitions) transitions_for[event] = transitions end |