Class: NodeVisitor

Inherits:
Object
  • Object
show all
Defined in:
lib/node_visitor.rb,
lib/node_visitor/version.rb

Defined Under Namespace

Classes: Adapter, InvalidAdapterError, ParserAdapter, PrismAdapter, SyntaxTreeAdapter

Constant Summary collapse

VERSION =
"1.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(adapter:) ⇒ NodeVisitor

Returns a new instance of NodeVisitor.



11
12
13
14
# File 'lib/node_visitor.rb', line 11

def initialize(adapter:)
  @adapter = get_adapter_instance(adapter)
  @callbacks = {}
end

Instance Method Details

#add_callback(node_type, at:, &block) ⇒ Object



16
17
18
19
# File 'lib/node_visitor.rb', line 16

def add_callback(node_type, at:, &block)
  @callbacks[node_type] ||= []
  @callbacks[node_type] << { block: block, at: at }
end

#visit(node, block_context = self) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/node_visitor.rb', line 21

def visit(node, block_context = self)
  return if @callbacks.empty?

  callbacks = @callbacks[:all]
  catch(:abort) do
    callbacks.each { |callback| block_context.instance_exec(node, &callback[:block]) if callback[:at] == 'start' } if callbacks
    visit_node(node, block_context)
    callbacks.each { |callback| block_context.instance_exec(node, &callback[:block]) if callback[:at] == 'end' } if callbacks
  end
end