Last active
December 17, 2015 05:38
-
-
Save dirk/5558853 to your computer and use it in GitHub Desktop.
The only state machine I'll (probably) ever need.
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
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