Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 46 lines (37 sloc) 0.857 kb
9b20d85 @soveran Initial commit
authored
1 class MicroMachine
589cc41 @soveran Added custom error for invalid events
authored
2 InvalidEvent = Class.new(NoMethodError)
3
b3df5b6 @soveran Updated README and changed micromachine API
authored
4 attr :transitions_for
9b20d85 @soveran Initial commit
authored
5 attr :state
6
7 def initialize initial_state
8 @state = initial_state
b3df5b6 @soveran Updated README and changed micromachine API
authored
9 @transitions_for = Hash.new
b4b3bba @soveran Added callbacks
authored
10 @callbacks = Hash.new { |hash, key| hash[key] = [] }
11 end
12
13 def on key, &block
14 @callbacks[key] << block
9b20d85 @soveran Initial commit
authored
15 end
16
a8815e6 @soveran Add when and events methods.
authored
17 def when(event, transitions)
18 transitions_for[event] = transitions
19 end
20
b3df5b6 @soveran Updated README and changed micromachine API
authored
21 def trigger event
a54c9dd @soveran Added trigger? method that returns true if the transition is valid
authored
22 if trigger?(event)
b3df5b6 @soveran Updated README and changed micromachine API
authored
23 @state = transitions_for[event][@state]
659bd1a @soveran Add keyword :any to add callbacks for any transition
authored
24 callbacks = @callbacks[@state] + @callbacks[:any]
25 callbacks.each { |callback| callback.call }
b4b3bba @soveran Added callbacks
authored
26 true
19e7d17 @soveran Change predicates to return booleans.
authored
27 else
28 false
9b20d85 @soveran Initial commit
authored
29 end
30 end
a54c9dd @soveran Added trigger? method that returns true if the transition is valid
authored
31
32 def trigger?(event)
19e7d17 @soveran Change predicates to return booleans.
authored
33 transitions_for[event][state] ? true : false
589cc41 @soveran Added custom error for invalid events
authored
34 rescue NoMethodError
35 raise InvalidEvent
a54c9dd @soveran Added trigger? method that returns true if the transition is valid
authored
36 end
6befbf5 @foca Allow comparing a Machine to a String
foca authored
37
a8815e6 @soveran Add when and events methods.
authored
38 def events
39 transitions_for.keys
40 end
41
6befbf5 @foca Allow comparing a Machine to a String
foca authored
42 def ==(some_state)
43 state == some_state
44 end
9b20d85 @soveran Initial commit
authored
45 end
Something went wrong with that request. Please try again.