Created
October 14, 2010 03:33
-
-
Save foca/625519 to your computer and use it in GitHub Desktop.
How to use the State pattern with MicroMachine, the simplest FSM lib out there :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This aims to reproduce the State pattern using MicroMachine. | |
# We're just implementing the example from http://github.com/dcadenas/state_pattern | |
require "micromachine" | |
module Stop | |
def self.color | |
"red" | |
end | |
def self.duration | |
3 | |
end | |
end | |
module Go | |
def self.color | |
"green" | |
end | |
def self.duration | |
2 | |
end | |
end | |
module Caution | |
def self.color | |
"yellow" | |
end | |
def self.duration | |
1 | |
end | |
end | |
street_light = MicroMachine.new(Stop).tap do |fsm| | |
fsm.transitions_for[:next] = { Stop => Go, | |
Go => Caution, | |
Caution => Stop } | |
fsm.on(:next) { sleep fsm.state.duration } | |
end | |
loop do | |
puts street_light.state.color | |
street_light.trigger(:next) | |
end | |
__END__ | |
Or, if you want delegation… | |
require "forwardable" | |
street_light.extend Forwardable | |
street_light.def_instance_delegators :state, :color, :duration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment