Class: Twig::Node::Cache

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/node/cache.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(arguments, body, lineno) ⇒ Cache

Returns a new instance of Cache.



6
7
8
# File 'lib/twig/node/cache.rb', line 6

def initialize(arguments, body, lineno)
  super({ arguments:, body: }, {}, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



10
11
12
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
# File 'lib/twig/node/cache.rb', line 10

def compile(compiler)
  compiler.
    add_debug_info(self).
    # Cache method just writes strings onto the buffer, it doesn't return the fragment
    # so we can capture any output to the main buffer and output that instead
    write("context.output_buffer.safe_append = context.call_context.capture do\n").
    indent.
    write('context.call_context.cache(')

  first = true
  nodes[:arguments].nodes.each_value do |argument|
    compiler.raw(', ') unless first
    first = false

    compiler.subcompile(argument)
  end

  compiler.
    raw(") do\n").
    indent.
    # inside a capture block the original buffer is capturing so it's OK if we push strings there
    write("context.original_buffer.safe_append = context.buffer_and_return do\n").
    indent

  compiler.
    write("context.push_stack\n").
    subcompile(nodes[:body]).
    raw("\n").
    write("context.pop_stack\n")

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