Class: Philiprehberger::XmlBuilder::Node
- Inherits:
-
Object
- Object
- Philiprehberger::XmlBuilder::Node
- Defined in:
- lib/philiprehberger/xml_builder/node.rb
Overview
Represents a single XML element with optional attributes and children.
Instance Attribute Summary collapse
-
#attributes ⇒ Object
readonly
Returns the value of attribute attributes.
-
#children ⇒ Object
readonly
Returns the value of attribute children.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
-
#initialize(name, attributes = {}) ⇒ Node
constructor
A new instance of Node.
-
#render(indent: nil, level: 0) ⇒ String
Render this node and its children as an XML string.
Constructor Details
#initialize(name, attributes = {}) ⇒ Node
Returns a new instance of Node.
11 12 13 14 15 |
# File 'lib/philiprehberger/xml_builder/node.rb', line 11 def initialize(name, attributes = {}) @name = name.to_s @attributes = attributes @children = [] end |
Instance Attribute Details
#attributes ⇒ Object (readonly)
Returns the value of attribute attributes.
7 8 9 |
# File 'lib/philiprehberger/xml_builder/node.rb', line 7 def attributes @attributes end |
#children ⇒ Object (readonly)
Returns the value of attribute children.
7 8 9 |
# File 'lib/philiprehberger/xml_builder/node.rb', line 7 def children @children end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
7 8 9 |
# File 'lib/philiprehberger/xml_builder/node.rb', line 7 def name @name end |
Instance Method Details
#render(indent: nil, level: 0) ⇒ String
Render this node and its children as an XML string.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/philiprehberger/xml_builder/node.rb', line 22 def render(indent: nil, level: 0) prefix = indent ? ' ' * (indent * level) : '' newline = indent ? "\n" : '' attrs = render_attributes tag_open = "#{prefix}<#{@name}#{attrs}" if @children.empty? "#{tag_open} />#{newline}" else parts = ["#{tag_open}>"] inline = !indent || @children.all?(String) if inline @children.each { |child| parts << render_child(child, indent: nil, level: 0) } parts << "</#{@name}>#{newline}" else parts[0] << newline @children.each { |child| parts << render_child(child, indent: indent, level: level + 1) } parts << "#{prefix}</#{@name}>#{newline}" end parts.join end end |