Class: ComponentEmbeddedRuby::Parser::TagParser

Inherits:
Base
  • Object
show all
Defined in:
lib/component_embedded_ruby/parser/tag_parser.rb

Overview

Internal: Parses an HTML tag into a Node object

This class is responsible for parsing an HTML element into a node instance. There are three variations of tags:

  • A self-closing tag e.g. <hr/>

  • A tag with no children <img src=“/favicon.png”></img>

  • A tag with children e.g. bold text!

A tag with children will delegate back to the ‘RootParser` since child elements can be any combination of adjacent tags, strings, and ruby code.

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from ComponentEmbeddedRuby::Parser::Base

Instance Method Details

#callObject



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
# File 'lib/component_embedded_ruby/parser/tag_parser.rb', line 18

def call
  # Expect opening carrot, e.g. < in <h1>
  expect(:open_carrot)

  # Expects an identifier, e.g. "h1"
  tag = expect(:identifier).value

  # Expects 0 or more attributes
  # e.g. id="hello" in <h1 id="hello">
  attributes = AttributeParser.new(token_reader).call

  # Is this a self-closing element?
  if current_token.type == :slash
    expect(:slash)
    expect(:close_carrot)

    Node.new(tag, attributes, [])
  else
    expect(:close_carrot)

    children = parse_children

    expect(:open_carrot)
    expect(:slash)
    close_tag = expect(:identifier).value

    raise "Mismatched tags. expected #{tag}, got #{current_token.value}" if close_tag != tag

    expect(:close_carrot)

    Node.new(tag, attributes, children)
  end
end