module StateMachine
   def self.included(klass)
    klass.extend(ClassMethods)
   end

   module ClassMethods
    def state(name, &block)
      self.send(:define_method, "state_#{name.to_s}", &block)
    end

    def transition(from, to, &block)
      self.send(:define_method, "trans_#{from.to_s}_to_#{to.to_s}", &block)
    end
  end

  def run_current_state
    send "state_#{current_state}"

    @regex ||= Regexp.compile /^trans_(.*)_to_(.*)$/
    methods.each do |method|
      matches = @regex.match method
      if matches && matches[1].to_s == current_state.to_s
        result = send(method)
        @current_state = matches[2].to_sym and return if result
      end
    end
  end
end

