Class: StateMachine::AlternateMachine

Inherits:
Object
  • Object
show all
Includes:
MatcherHelpers
Defined in:
lib/state_machine/alternate_machine.rb

Overview

Provides an alternate syntax for defining state machines

For example,

class Vehicle
  state_machine :initial => :parked, :action => :save, :syntax => :alternate do
    state :parked do
      event :ignite, :to => :idling, :if => :have_keys?
    end

    state :idling do
      event :park, :to => :parked, :unless => :no_spots?
    end
  end
end

Instead of,

class Vehicle
  state_machine :initial => :parked, :action => :save do
    event :ignite do
      transition :parked => :idling, :if => :have_keys?
    end

    event :park do
      transition :idling => :parked, :unless => :no_spots?
    end
  end
end

Also supports usage of :any, :all, and :same as valid states.

Defined Under Namespace

Classes: InvalidEventError

Instance Method Summary collapse

Methods included from MatcherHelpers

#all, #same

Constructor Details

#initialize(&block) ⇒ AlternateMachine



39
40
41
42
# File 'lib/state_machine/alternate_machine.rb', line 39

def initialize(&block)
  @queued_sends = []
  instance_eval(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object



75
76
77
# File 'lib/state_machine/alternate_machine.rb', line 75

def method_missing(*args, &block)
  @queued_sends << [args, block]
end

Instance Method Details

#event(event_name, options = {}) ⇒ Object

Raises:



51
52
53
54
55
# File 'lib/state_machine/alternate_machine.rb', line 51

def event(event_name, options = {})
  to_state = options.delete(:to)
  raise InvalidEventError.new("event must be called within a state definition") unless @from_state
  @queued_sends << [event_name, @from_state, to_state, options]
end

#state(*args, &block) ⇒ Object



44
45
46
47
48
49
# File 'lib/state_machine/alternate_machine.rb', line 44

def state(*args, &block)
  @from_state = args.first
  instance_eval(&block) if block_given?
ensure
  @from_state = nil
end

#to_state_machineObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/state_machine/alternate_machine.rb', line 57

def to_state_machine
  queued_sends = @queued_sends
  Proc.new {
    queued_sends.each do |args|
      case args.length
      when 2 # method_missing
        args, block = args
        send(*args, &block)
      when 4 # event transition
        event_name, from, to, options = args
        event event_name do
          transition options.merge(from => to)
        end
      end
    end
  }
end