Class: Vapid::Template::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/vapid/template/parser.rb

Overview

TODO:

Possibly use something other than Nokogiri, since it automatically adds DOCTYPE, etc

HTML parser and DOM walker

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html, initial_context) ⇒ Parser

Returns a new instance of Parser.



9
10
11
12
# File 'lib/vapid/template/parser.rb', line 9

def initialize(html, initial_context)
  @doc = Nokogiri::HTML(html)
  @context_stack = [initial_context]
end

Instance Attribute Details

#docObject

Returns the value of attribute doc.



7
8
9
# File 'lib/vapid/template/parser.rb', line 7

def doc
  @doc
end

Instance Method Details

#to_htmlObject

rubocop:enable MethodLength



33
34
35
# File 'lib/vapid/template/parser.rb', line 33

def to_html
  @doc.to_html
end

#walk(node = doc_root, set_context: nil) {|node, @context_stack| ... } ⇒ Object

rubocop:disable MethodLength

Yields:

  • (node, @context_stack)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/vapid/template/parser.rb', line 15

def walk(node = doc_root, set_context: nil, &block)
  if node.group?
    context = set_context.present? ? set_context.call(node.group_expr) : node.group_expr
    push_context(context)
  end

  yield(node, *@context_stack) if node.directives?

  next_node = node.first_child
  while next_node
    walk(next_node, set_context: set_context, &block)
    next_node = next_node.next_sibling
  end

  pop_context if node.group?
end