Class: Twig::TokenParser::Guard

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/token_parser/guard.rb

Overview

Prevents compilation of block if function/filter/test does not exist. Since this is at compilation time, this DOES NOT work with Rails helper functions as those can’t be determined fully at compile time as of now.

Instance Attribute Summary

Attributes inherited from Base

#parser

Instance Method Summary collapse

Instance Method Details

#parse(token) ⇒ Object



9
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
48
49
50
51
52
53
54
# File 'lib/twig/token_parser/guard.rb', line 9

def parse(token)
  stream = parser.stream
  type_token = stream.expect(Token::NAME_TYPE)

  unless %w[function filter test].include?(type_token.value)
    raise Error::Syntax.new(
      "Supported guard types are function, filter, and test, \"#{token.value}\" given.",
      type_token.lineno,
      stream.source
    )
  end

  name_token = stream.expect(Token::NAME_TYPE)
  name = name_token.value

  if type_token.value == 'test' && stream.test(Token::NAME_TYPE)
    name = "#{name} #{stream.current.value}"
    stream.next
  end

  begin
    exists = !parser.environment.send(type_token.value, name).nil?
  rescue Error::Syntax
    exists = false
  end

  stream.expect(Token::BLOCK_END_TYPE)

  if exists
    body = parser.subparse(method(:decide_guard_fork))
  else
    body = Node::Empty.new
    parser.subparse_ignore_unknown_twig_callables(method(:decide_guard_fork))
  end

  else_node = Node::Empty.new

  if stream.next.value == 'else'
    stream.expect(Token::BLOCK_END_TYPE)
    else_node = parser.subparse(method(:decide_guard_end), drop_needle: true)
  end

  stream.expect(Token::BLOCK_END_TYPE)

  Node::Nodes.new(AutoHash.new.add(exists ? body : else_node))
end

#tagObject



56
57
58
# File 'lib/twig/token_parser/guard.rb', line 56

def tag
  'guard'
end