Class: StateMachine
- Inherits:
-
Object
- Object
- StateMachine
- Defined in:
- lib/rms.rb
Overview
Usage:
require 'rms'
class Blub < StateMachine
def initialize
super :welcome
@name = 'World'
end
def welcome_enter(env)
puts 'Enter Name: '
end
def welcome(env)
@name = env[:line] if env[:line] != ''
puts "Hello #{@name}"
end
end
bla = Blub.new
# prints out 'Enter Name: '
loop do
line = gets.strip
bla.process({:line => line})
end
Direct Known Subclasses
Instance Method Summary collapse
-
#initialize(start_state = :start, error_state = :error) ⇒ StateMachine
constructor
A new instance of StateMachine.
- #process(env) ⇒ Object
- #switch(new_state, env) ⇒ Object
Constructor Details
#initialize(start_state = :start, error_state = :error) ⇒ StateMachine
Returns a new instance of StateMachine.
26 27 28 29 30 |
# File 'lib/rms.rb', line 26 def initialize(start_state=:start, error_state=:error) @error_state = error_state @state = :none switch(start_state, {}) end |
Instance Method Details
#process(env) ⇒ Object
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/rms.rb', line 45 def process(env) unless @state_method begin @state_method = method(@state) rescue NameError switch(@error_state, env) end end @state_method.call(env) end |
#switch(new_state, env) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/rms.rb', line 32 def switch(new_state, env) # call the enter method... begin m_enter = method((new_state.to_s + '_enter').to_sym) m_enter.call(env) rescue NameError # nope didnt exist end # now check if there is such a method(with the name new_state) @state_method = method(new_state.to_sym) @state = new_state.to_sym end |