Class: Twig::Node::Expression::Filter::Default

Inherits:
Twig::Node::Expression::Filter show all
Defined in:
lib/twig/node/expression/filter/default.rb

Overview

Returns the value or the default value when it is undefined or empty.

var.foo|default(‘foo item on var is not defined’) }

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(node, filter, arguments, lineno) ⇒ Default

Returns a new instance of Default.

Parameters:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/twig/node/expression/filter/default.rb', line 15

def initialize(node, filter, arguments, lineno)
  name = filter.name
  default = Expression::Filter.new(node, filter, arguments, node.lineno)

  if name == 'default' && (node.is_a?(Variable::Context) || node.is_a?(GetAttribute))
    test = Test::Defined.new(node.dup, TwigTest.new('defined'), Empty.new, node.lineno)
    false_case = arguments.empty? ? Expression::Constant.new('', node.lineno) : arguments.nodes[0]
    node = Ternary.new(test, default, false_case, node.lineno)
  else
    node = default
  end

  super
end

Instance Method Details

#compile(compiler) ⇒ Object



30
31
32
# File 'lib/twig/node/expression/filter/default.rb', line 30

def compile(compiler)
  compiler.subcompile(nodes[:node])
end