Skip to content

Instantly share code, notes, and snippets.

@dirk
Last active December 17, 2015 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirk/5558853 to your computer and use it in GitHub Desktop.
Save dirk/5558853 to your computer and use it in GitHub Desktop.
The only state machine I'll (probably) ever need.
class StateMachine
def initialize
@transitions = {}
end
def transition(opts, &block)
from = opts[:from]
to = opts[:to]
@transitions[from] ||= {}
@transitions[from][to] = block
end
def transition!(from, to, *args)
if @transitions.has_key?(from) && @transitions[from].has_key?(to)
@transitions[from][to].call(*args)
return to
else
raise "Cannot transition from #{from.inspect} to #{to.inspect}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment