Class: MicroFSM
- Inherits:
-
Object
- Object
- MicroFSM
- Defined in:
- lib/version.rb,
lib/microfsm.rb
Constant Summary collapse
- VERSION =
2021-01-24
'0.0.1'- InvalidEvent =
Class.new(NoMethodError)
- InvalidState =
Class.new(ArgumentError)
- InvalidTransition =
Class.new(ArgumentError)
Instance Attribute Summary collapse
-
#state ⇒ Object
readonly
Returns the value of attribute state.
Instance Method Summary collapse
- #events ⇒ Object
-
#initialize(initial_state) ⇒ MicroFSM
constructor
A new instance of MicroFSM.
- #states ⇒ Object
- #trigger(event) ⇒ Object
- #trigger!(event) ⇒ Object
- #trigger?(event) ⇒ Boolean
- #triggerable_events ⇒ Object
- #when(event, transitions, &block) ⇒ Object
Constructor Details
#initialize(initial_state) ⇒ MicroFSM
Returns a new instance of MicroFSM.
10 11 12 13 14 |
# File 'lib/microfsm.rb', line 10 def initialize(initial_state) @state = initial_state @transitions_for = {} @callbacks_for = {} end |
Instance Attribute Details
#state ⇒ Object (readonly)
Returns the value of attribute state.
8 9 10 |
# File 'lib/microfsm.rb', line 8 def state @state end |
Instance Method Details
#events ⇒ Object
46 47 48 |
# File 'lib/microfsm.rb', line 46 def events @transitions_for.keys.sort end |
#states ⇒ Object
54 55 56 |
# File 'lib/microfsm.rb', line 54 def states @transitions_for.values.map(&:to_a).flatten.uniq.sort end |
#trigger(event) ⇒ Object
31 32 33 |
# File 'lib/microfsm.rb', line 31 def trigger(event) trigger?(event) and transit(event) end |
#trigger!(event) ⇒ Object
35 36 37 38 |
# File 'lib/microfsm.rb', line 35 def trigger!(event) trigger(event) or raise InvalidState.new("Event '#{event}' not valid from state '#{@state}'") end |
#trigger?(event) ⇒ Boolean
40 41 42 43 44 |
# File 'lib/microfsm.rb', line 40 def trigger?(event) raise InvalidEvent unless @transitions_for.has_key?(event) @transitions_for[event].has_key?(state) end |
#triggerable_events ⇒ Object
50 51 52 |
# File 'lib/microfsm.rb', line 50 def triggerable_events events.select { |event| trigger?(event) }.sort end |
#when(event, transitions, &block) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# 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_given? end self end |