Class: Philiprehberger::HtmlBuilder::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/html_builder/node.rb

Overview

Represents an HTML element node with tag, attributes, and children

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tag, attributes: {}) ⇒ Node

Returns a new instance of Node.

Parameters:

  • tag (Symbol)

    the HTML tag name

  • attributes (Hash) (defaults to: {})

    HTML attributes



18
19
20
21
22
# File 'lib/philiprehberger/html_builder/node.rb', line 18

def initialize(tag, attributes: {})
  @tag = tag
  @attributes = attributes
  @children = []
end

Instance Attribute Details

#attributesHash (readonly)

Returns the element attributes.

Returns:

  • (Hash)

    the element attributes



11
12
13
# File 'lib/philiprehberger/html_builder/node.rb', line 11

def attributes
  @attributes
end

#childrenArray (readonly)

Returns the child nodes.

Returns:

  • (Array)

    the child nodes



14
15
16
# File 'lib/philiprehberger/html_builder/node.rb', line 14

def children
  @children
end

#tagSymbol (readonly)

Returns the tag name.

Returns:

  • (Symbol)

    the tag name



8
9
10
# File 'lib/philiprehberger/html_builder/node.rb', line 8

def tag
  @tag
end

Instance Method Details

#add_child(child) ⇒ void

This method returns an undefined value.

Add a child node

Parameters:

  • child (Node, String)

    child node or text content



28
29
30
# File 'lib/philiprehberger/html_builder/node.rb', line 28

def add_child(child)
  @children << child
end

#to_html(indent: nil, indent_size: 2) ⇒ String

Render the node to an HTML string

Parameters:

  • indent (Integer, nil) (defaults to: nil)

    current indentation level (nil for minified)

  • indent_size (Integer) (defaults to: 2)

    number of spaces per indent level

Returns:

  • (String)

    the rendered HTML



37
38
39
40
41
42
43
44
45
# File 'lib/philiprehberger/html_builder/node.rb', line 37

def to_html(indent: nil, indent_size: 2)
  flat_attrs = flatten_attributes(attributes)

  if indent
    render_pretty(flat_attrs, indent: indent, indent_size: indent_size)
  else
    render_inline(flat_attrs)
  end
end