Class: Einvoicing::XMLBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/einvoicing/xml_builder.rb

Overview

Minimal zero-dependency XML builder used internally by format generators. Produces indented XML with proper attribute and text escaping.

Instance Method Summary collapse

Constructor Details

#initializeXMLBuilder

Returns a new instance of XMLBuilder.



7
8
9
10
# File 'lib/einvoicing/xml_builder.rb', line 7

def initialize
  @parts = [ '<?xml version="1.0" encoding="UTF-8"?>' ]
  @depth = 0
end

Instance Method Details

#tag(name, attrs = {}, &block) ⇒ Object

Build a non-empty element with an optional block for children. If the block yields no content, the element is omitted entirely.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/einvoicing/xml_builder.rb', line 14

def tag(name, attrs = {}, &block)
  attr_str = serialize_attrs(attrs)
  if block
    opening = "#{indent}<#{name}#{attr_str}>"
    @parts << opening
    size_before = @parts.size
    @depth += 1
    yield
    @depth -= 1
    if @parts.size == size_before
      # Block yielded nothing — remove the opening tag.
      @parts.pop
    else
      @parts << "#{indent}</#{name}>"
    end
  else
    @parts << "#{indent}<#{name}#{attr_str}/>"
  end
end

#text(name, value, attrs = {}) ⇒ Object

Build a text element: value.



35
36
37
38
39
40
# File 'lib/einvoicing/xml_builder.rb', line 35

def text(name, value, attrs = {})
  return if value.nil?

  attr_str = serialize_attrs(attrs)
  @parts << "#{indent}<#{name}#{attr_str}>#{escape(value.to_s)}</#{name}>"
end

#to_xmlObject



42
43
44
# File 'lib/einvoicing/xml_builder.rb', line 42

def to_xml
  @parts.join("\n")
end