Class: Twig::Node::Expression::ArrowFunction

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

Instance Attribute Summary

Attributes inherited from Base

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

Instance Method Summary collapse

Methods inherited from Base

#explicit_parentheses?, #set_explicit_parentheses

Methods inherited from Base

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

Constructor Details

#initialize(expr, names, lineno) ⇒ ArrowFunction

Returns a new instance of ArrowFunction.

Parameters:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/twig/node/expression/arrow_function.rb', line 10

def initialize(expr, names, lineno)
  if !names.is_a?(Expression::Array) && !names.is_a?(Expression::Variable::Context)
    raise Error::Syntax.new(
      'The arrow function argument must be a list of variables or a single variable.',
      names.lineno,
      names.source_context
    )
  end

  if names.is_a?(Expression::Variable::Context)
    names = Expression::Array.new(AutoHash.new.add(
      Expression::Variable::AssignContext.new(names.attributes[:name], names.lineno)
    ), names.lineno)
  end

  super({ expr:, names: }, {}, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/twig/node/expression/arrow_function.rb', line 28

def compile(compiler)
  compiler.
    add_debug_info(self).
    raw('-> (')

  first = true
  nodes[:names].each_value do |name|
    compiler.raw(', ') unless first
    compiler.raw("__#{name.attributes[:name]}__")
    first = false
  end

  compiler.raw(') { ')

  nodes[:names].nodes.each_value do |name|
    compiler.
      raw("context[:#{name.attributes[:name]}] = ").
      raw("__#{name.attributes[:name]}__; ")
  end

  compiler.
    subcompile(nodes[:expr]).
    raw('}')
end