Class: DTC::Utils::Visitor::Switcher

Inherits:
Forwarder
  • Object
show all
Defined in:
lib/dtc/utils/visitor.rb

Overview

Base class for visitors that redirect their calls to other visitors for sub-branches.

Override ‘visitor_for_subtree` and return a new visitor to begin receiving calls below current symbol.

When the branch is visited and after the new visitor is popped, ‘visitor_left_subtree` is called with original arguments as given to `enter`.

Instance Attribute Summary

Attributes inherited from Forwarder

#next_visitor

Instance Method Summary collapse

Methods inherited from Forwarder

#add

Constructor Details

#initialize(receiver) ⇒ Switcher

Returns a new instance of Switcher.



41
42
43
44
45
# File 'lib/dtc/utils/visitor.rb', line 41

def initialize receiver
  @visitor_full_stack = [receiver]
  @visitor_stack = [[receiver]]
  super receiver
end

Instance Method Details

#enter(*args) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/dtc/utils/visitor.rb', line 46

def enter *args
  sub_visitor = visitor_for_subtree(*args)
  @visitor_full_stack.push(sub_visitor)
  if sub_visitor
    @visitor_stack.push([sub_visitor, *args])
    self.next_visitor = sub_visitor
  else
    super
  end
end

#leaveObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/dtc/utils/visitor.rb', line 56

def leave
  visitor = @visitor_full_stack.pop
  if visitor
    previous_visitor = @visitor_stack.pop
    self.next_visitor = (@visitor_stack.last || []).first
    visitor_left_subtree *previous_visitor
  else
    super
  end
end