module MouseOrgan

A tiny mixin to turn a class into a state machine. Example:

class Foo

include MouseOrgan

def initialize
  machine_start(:one)
end

def state_one
  transition_to :two
  sleep 1
end

def state_two
  transition_to :three
  sleep 1
end

def state_three
  throw :machine_stop
end

def transition_to(state)
  puts state
  super
end

end

Constants

VERSION

Public Instance Methods

machine_start(initial) click to toggle source
# File lib/mouse_organ.rb, line 36
def machine_start(initial)
  transition_to initial

  catch :machine_stop do
    loop do
      send state_method(@state)
      throw :machine_stop if machine_stop?
    end
  end

  self
end
machine_stop?() click to toggle source
# File lib/mouse_organ.rb, line 59
def machine_stop?
  false
end
transition_to(state) click to toggle source
# File lib/mouse_organ.rb, line 49
def transition_to(state)
  if self.respond_to? state_method(state)
    @state = state
  else
    fail ArgumentError, "Unknown state '#{state}'"
  end

  self
end

Private Instance Methods

state_method(state) click to toggle source
# File lib/mouse_organ.rb, line 65
def state_method(state)
  "state_#{state}".to_sym
end