Class: Pushdown::Transition::Switch

Inherits:
Pushdown::Transition show all
Defined in:
lib/pushdown/transition/switch.rb

Overview

A switch transition – remove the current state from the stack and add a different one.

Instance Attribute Summary collapse

Attributes inherited from Pushdown::Transition

#name

Instance Method Summary collapse

Methods inherited from Pushdown::Transition

inherited, #type_name

Constructor Details

#initialize(name, state_class, data = nil) ⇒ Switch

Create a transition that will Switch the current State with an instance of the given state_class on the stack.



13
14
15
16
17
18
# File 'lib/pushdown/transition/switch.rb', line 13

def initialize( name, state_class, data=nil )
  super( name )

  @state_class = state_class
  @data = data
end

Instance Attribute Details

#dataObject (readonly)

The data object to pass to the #state_class’s constructor



31
32
33
# File 'lib/pushdown/transition/switch.rb', line 31

def data
  @data
end

#state_classObject (readonly)

The State to push to.



27
28
29
# File 'lib/pushdown/transition/switch.rb', line 27

def state_class
  @state_class
end

Instance Method Details

#apply(stack) ⇒ Object

Apply the transition to the given stack.

Raises:

  • (Pushdown::TransitionError)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/pushdown/transition/switch.rb', line 35

def apply( stack )
  raise Pushdown::TransitionError, "can't switch on an empty stack" if stack.empty?

  state = self.state_class.new( self.data )

  self.log.debug "switching current state with a new state: %p" % [ state ]
  old_state = stack.pop
  old_state.on_stop if old_state

  stack.push( state )
  state.on_start

  return stack
end