Class: OpenXml::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/openxml/builder.rb,
lib/openxml/builder/element.rb

Defined Under Namespace

Classes: Element

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|_self| ... } ⇒ Builder

Returns a new instance of Builder.

Yields:

  • (_self)

Yield Parameters:


13
14
15
16
17
18
19
20
21
22
# File 'lib/openxml/builder.rb', line 13

def initialize(options={})
  @to_s_options = { with_xml: true }

  @document = Ox::Document.new(
    encoding: "utf-8",
    version: "1.0",
    standalone: options[:standalone])
  @parent = @document
  yield self if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(tag_name, *args) ⇒ Object


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/openxml/builder.rb', line 40

def method_missing(tag_name, *args)
  new_element = OpenXml::Builder::Element.new(tag_name)
  attributes = extract_options!(args)
  attributes.each do |key, value|
    new_element[key] = value
  end

  new_element.namespace = @ns
  @ns = nil

  if block_given?
    begin
      was_current = @parent
      @parent = new_element
      yield self
    ensure
      @parent = was_current
    end
  elsif value = args.first
    new_element << value.to_s
  end

  @parent << new_element.__getobj__
end

Instance Attribute Details

#parentObject (readonly)

Returns the value of attribute parent


11
12
13
# File 'lib/openxml/builder.rb', line 11

def parent
  @parent
end

Instance Method Details

#[](ns) ⇒ Object


35
36
37
38
# File 'lib/openxml/builder.rb', line 35

def [](ns)
  @ns = ns.to_sym if ns
  return self
end

#to_s(args = {}) ⇒ Object Also known as: to_xml


24
25
26
27
28
29
30
31
32
# File 'lib/openxml/builder.rb', line 24

def to_s(args={})
  options = @to_s_options

  # Unless we would like to debug the files,
  # don't add whitespace during generation.
  options = options.merge(indent: -1) unless args[:debug]

  Ox.dump(@document, options).strip
end