Skip to content

Instantly share code, notes, and snippets.

@chooper
Created November 1, 2013 20:53
Show Gist options
  • Save chooper/7271783 to your computer and use it in GitHub Desktop.
Save chooper/7271783 to your computer and use it in GitHub Desktop.
Just some playing around with a state machine representing a door that can lock, with "locked" being a separate state from "closed"
sub@asdf:~/projects/fsm$ irb -I
irb(main):001:0> require './door.rb'
=> true
irb(main):002:0> front_door = Door.new
=> #<Door:0x00000001913ab0 @state="closed">
irb(main):003:0> front_door.open_
Transition: closed => open
=> true
irb(main):004:0> front_door.close
Transition: open => closed
=> true
irb(main):005:0> front_door.lock
Transition: closed => locked
=> true
irb(main):006:0> front_door.open_
=> false
irb(main):007:0> front_door.close
=> false
irb(main):008:0> front_door.unlock
Transition: locked => closed
=> true
irb(main):009:0> front_door.close
=> false
irb(main):010:0> front_door.open_
Transition: closed => open
=> true
irb(main):011:0>
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require 'state_machine'
class Door
state_machine :state, :initial => :closed do
after_transition any => any do |door, transition|
puts "Transition: #{transition.from} => #{transition.to}"
end
event :open_ do
transition :closed => :open
end
event :close do
transition :open => :closed
end
event :lock do
transition :closed => :locked
end
event :unlock do
transition :locked => :closed
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment