Class: Giter8::AST

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/giter8/ast.rb

Overview

AST represents a set of nodes of a template file

Constant Summary collapse

LEADING_LINEBREAK_REGEXP =
/^\r?\n/.freeze

Instance Method Summary collapse

Constructor Details

#initializeAST

Returns a new instance of AST.



10
11
12
# File 'lib/giter8/ast.rb', line 10

def initialize
  @nodes = []
end

Instance Method Details

#cleanObject

Returns a new AST node containing this node’s after cleaning them.



61
62
63
64
65
# File 'lib/giter8/ast.rb', line 61

def clean
  ast = AST.new
  ast.push(*each_with_index.map(&method(:clean_node)).reject(&:nil?))
  ast
end

#clean!Object

Cleans up this AST’s nodes in-place.



24
25
26
# File 'lib/giter8/ast.rb', line 24

def clean!
  @nodes = clean.instance_variable_get(:@nodes)
end

#clean_conditional_ast(node) ⇒ Object

Cleans leading linebreaks from the provided node



29
30
31
32
33
34
35
36
37
# File 'lib/giter8/ast.rb', line 29

def clean_conditional_ast(node)
  return node if node.empty? || !node.first.is_a?(Literal)

  cond = node.first
  cond.value.sub!(LEADING_LINEBREAK_REGEXP, "")
  node.shift
  node.unshift(cond) unless cond.value.empty?
  node
end

#clean_node(node, idx) ⇒ Object

clean_node attempts to sanitise a provide node under a given index in this AST



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/giter8/ast.rb', line 41

def clean_node(node, idx)
  if node.is_a?(Conditional)
    # Remove leading linebreak from ASTs inside conditionals
    node.cond_then = clean_conditional_ast(node.cond_then.clean)
    node.cond_else = clean_conditional_ast(node.cond_else.clean)

    # cond_else_if contains a list of Condition objects, which
    # need special handling.
    node.cond_else_if.clean!
  end

  if node.is_a?(Literal) && idx.positive? && self[idx - 1].is_a?(Conditional)
    # Remove leading linebreak from Literals following conditionals
    node.value.sub!(LEADING_LINEBREAK_REGEXP, "")
    return if node.value.empty?
  end
  node
end

#pure_literal?Boolean

Returns whether this AST node is composed exclusively by Literals

Returns:

  • (Boolean)


19
20
21
# File 'lib/giter8/ast.rb', line 19

def pure_literal?
  all? { |v| v.is_a? Literal }
end