Skip to content

Instantly share code, notes, and snippets.

@foca
Created October 14, 2010 03:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save foca/625519 to your computer and use it in GitHub Desktop.
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 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