Class: OpenXml::Builder

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

Defined Under Namespace

Classes: Element, Namespace

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Builder.

Yields:

  • (_self)

Yield Parameters:



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

def initialize(options={})
  @options = {
    with_xml: true,
    encoding: "utf-8"
  }.merge(options)
  @options[:with_xml] = !!@options[:with_xml] || @options[:standalone] == :yes

  @document = Ox::Document.new({version: "1.0"}.merge(@options))
  @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



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/openxml/builder.rb', line 48

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

  # Adapted from Nokogiri's builder.rb
  if @ns.is_a? OpenXml::Builder::Namespace
    new_element.namespace = @ns
  elsif @ns.is_a? Hash
    new_element.namespace = new_element.namespace_definitions.find { |x| x.prefix == @ns[:pending] }
    raise ArgumentError, "Namespace #{@ns[:pending]} has not been defined" if new_element.namespace.nil?
  end

  @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.



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

def parent
  @parent
end

Instance Method Details

#[](ns) ⇒ Object

Adapted from Nokogiri’s builder.rb



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/openxml/builder.rb', line 32

def [](ns)
  if @parent != @document
    @ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s }
  end
  return self if @ns

  @parent.ancestors.each do |a|
    next if a == @document
    @ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s }
    return self if @ns
  end

  @ns = { :pending => ns.to_s }
  return self
end

#to_sObject Also known as: to_xml



26
27
28
# File 'lib/openxml/builder.rb', line 26

def to_s
  Ox.dump @document, @options
end