Class: Haml::Parser::ParseNode

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/haml.rb

Instance Method Summary collapse

Instance Method Details

#accept(visitor) ⇒ Object

Here we’re going to hook into the parse node and define a method that will accept a visitor in order to walk through the tree.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/syntax_tree/haml.rb', line 60

def accept(visitor)
  case type
  when :comment
    visitor.visit_comment(self)
  when :doctype
    visitor.visit_doctype(self)
  when :filter
    visitor.visit_filter(self)
  when :haml_comment
    visitor.visit_haml_comment(self)
  when :plain
    visitor.visit_plain(self)
  when :root
    visitor.visit_root(self)
  when :script
    visitor.visit_script(self)
  when :silent_script
    visitor.visit_silent_script(self)
  when :tag
    visitor.visit_tag(self)
  else
    raise "Unknown node type: #{type}"
  end
end

#format(q) ⇒ Object

This is our entrypoint for the formatter. We effectively delegate this to accepting the Format visitor.



87
88
89
# File 'lib/syntax_tree/haml.rb', line 87

def format(q)
  accept(SyntaxTree::Haml::Format.new(q))
end

#last_lineObject

When we’re formatting a list of children, we need to know the last line a node is on. This is because the next node in the list of children should be at most 1 blank line below the last line of the previous node. We cache this because at worst it requires walking the entire tree because filter nodes can take up multiple lines.



96
97
98
99
100
101
102
103
104
105
# File 'lib/syntax_tree/haml.rb', line 96

def last_line
  @last_line ||=
    if children.any?
      children.last.last_line
    elsif type == :filter
      line + value[:text].rstrip.count("\n") + 1
    else
      line
    end
end

#pretty_print(q) ⇒ Object

This is our entrypoint for the pretty printer. We effectively delegate this to accepting the PrettyPrint visitor.



109
110
111
# File 'lib/syntax_tree/haml.rb', line 109

def pretty_print(q)
  accept(SyntaxTree::Haml::PrettyPrint.new(q))
end