Class: DocxGenerator::Element

Inherits:
Object
  • Object
show all
Defined in:
lib/docx_generator/element.rb

Overview

Represent an XML element. This class should not be used directly by the users of the library.

Instance Method Summary collapse

Constructor Details

#initialize(name, attributes = {}, content = []) ⇒ Element

Create a new XML element.

Parameters:

  • name (String)

    The name of the XML element.

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

    The attributes of the XML element.

  • content (Array) (defaults to: [])

    An array of the children of the XML element (other XML elements).



10
11
12
13
14
# File 'lib/docx_generator/element.rb', line 10

def initialize(name, attributes = {}, content = [])
  @name = name
  @attributes = attributes
  @content = content
end

Instance Method Details

#add(element) ⇒ Object

Add an XML element in the content of this XML element.

Parameters:



18
19
20
# File 'lib/docx_generator/element.rb', line 18

def add(element)
  @content << element
end

#generateString Also known as: to_s

Generate the XML for the element.

Returns:

  • (String)

    The XML produced for the element.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/docx_generator/element.rb', line 24

def generate
  output = ""
  if @content.length != 0
    output += "<#{@name}#{generate_attributes}>"
    @content.each do |element|
      if element.respond_to?(:generate)
        output += element.generate
      else
        output += element.to_s
      end
    end
    output += "</#{@name}>"
  else
    output += "<#{@name}#{generate_attributes} />"
  end
  output
end