Class: Liquid::ParseTreeVisitor

Inherits:
Object
  • Object
show all
Defined in:
lib/liquid/parse_tree_visitor.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node, callbacks) ⇒ ParseTreeVisitor

Returns a new instance of ParseTreeVisitor.



13
14
15
16
# File 'lib/liquid/parse_tree_visitor.rb', line 13

def initialize(node, callbacks)
  @node = node
  @callbacks = callbacks
end

Class Method Details

.for(node, callbacks = Hash.new(proc {})) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/liquid/parse_tree_visitor.rb', line 5

def self.for(node, callbacks = Hash.new(proc {}))
  if defined?(node.class::ParseTreeVisitor)
    node.class::ParseTreeVisitor
  else
    self
  end.new(node, callbacks)
end

Instance Method Details

#add_callback_for(*classes, &block) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/liquid/parse_tree_visitor.rb', line 18

def add_callback_for(*classes, &block)
  callback = block
  callback = ->(node, _) { yield node } if block.arity.abs == 1
  callback = ->(_, _) { yield } if block.arity.zero?
  classes.each { |klass| @callbacks[klass] = callback }
  self
end

#visit(context = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/liquid/parse_tree_visitor.rb', line 26

def visit(context = nil)
  children.map do |node|
    item, new_context = @callbacks[node.class].call(node, context)
    [
      item,
      ParseTreeVisitor.for(node, @callbacks).visit(new_context || context)
    ]
  end
end