Class: Twig::Node::If

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/node/if.rb

Instance Attribute Summary

Attributes inherited from Base

#attributes, #lineno, #nodes, #source_context, #tag

Instance Method Summary collapse

Methods inherited from Base

#empty?, #length, #template_name, #to_s

Constructor Details

#initialize(tests, else_node, lineno) ⇒ If

Returns a new instance of If.



6
7
8
9
10
11
# File 'lib/twig/node/if.rb', line 6

def initialize(tests, else_node, lineno)
  nodes = { tests: }
  nodes[:else] = else_node if else_node

  super(nodes, {}, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/twig/node/if.rb', line 13

def compile(compiler)
  compiler.add_debug_info(self)

  (0...nodes[:tests].nodes.length).step(2).each do |i|
    if i.zero?
      compiler.
        raw("\n").
        write('if (')
    else
      compiler.
        outdent.
        write('elsif (')
    end

    compiler.
      raw('::Twig::Extension::Core.bool(').
      subcompile(nodes[:tests].nodes[i]).
      raw("))\n").
      indent

    if nodes[:tests].nodes.key?(i + 1)
      compiler.
        subcompile(nodes[:tests].nodes[i + 1])
    end
  end

  if nodes.key?(:else)
    compiler.
      outdent.
      write("else\n").
      indent.
      subcompile(nodes[:else])
  end

  compiler.
    outdent.
    write("end\n\n")
end