Class: FSM::FSMState
- Inherits:
-
Object
- Object
- FSM::FSMState
- Defined in:
- lib/barebone-fsm.rb
Overview
FSMState class represents a state of the finite state machine.
Usage
state = FSMState.new :state_name
state.event(:event_name) do # creates the event when block is given
puts "#{@event} triggered on state #{@state}"
:new_state
end
puts state
state.event :event_name # triggers the event when block is absent
Instance Attribute Summary collapse
-
#state ⇒ Object
readonly
The readonly state variable represents an unique state.
Instance Method Summary collapse
-
#build(&build_block) ⇒ Object
(also: #run)
The #build/#run method sets up the events as given in the build_block.
-
#event(event_name, &event_block) ⇒ Object
When the event_block is provided, it sets up a new event for this state.
-
#initialize(state_name) ⇒ FSMState
constructor
A new instance of FSMState.
- #to_s ⇒ Object
Constructor Details
#initialize(state_name) ⇒ FSMState
Returns a new instance of FSMState.
38 39 40 41 |
# File 'lib/barebone-fsm.rb', line 38 def initialize(state_name) @state = state_name @events = {} end |
Instance Attribute Details
#state ⇒ Object (readonly)
The readonly state variable represents an unique state. Though it can have any data type, usage of symbol or string is preferable.
36 37 38 |
# File 'lib/barebone-fsm.rb', line 36 def state @state end |
Instance Method Details
#build(&build_block) ⇒ Object Also known as: run
The #build/#run method sets up the events as given in the build_block. Only event method is supported within the build_block with the name of the event and an optional block supplied. The operation for each such line is carried out by the #event method.
68 69 70 |
# File 'lib/barebone-fsm.rb', line 68 def build(&build_block) self.instance_eval &build_block end |
#event(event_name, &event_block) ⇒ Object
When the event_block is provided, it sets up a new event for this state. Otherwise, when the event_block is missing, the event_name is triggered. If the event is nil or not already setup, then the default event is triggered.
53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/barebone-fsm.rb', line 53 def event(event_name, &event_block) if event_name and block_given? then @events[event_name] = event_block elsif event_name and @events.has_key? event_name then @event = event_name self.instance_eval &@events[@event] elsif @events.has_key? :default then @event = :default self.instance_eval &@events[@event] end end |
#to_s ⇒ Object
43 44 45 46 47 48 |
# File 'lib/barebone-fsm.rb', line 43 def to_s() @state.to_s + ": [" + @events.keys.map(&:to_s).join(', ') + "]" end |