Class: XMLBuilder

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

Overview

XMLBuilder is a class that allows you to easily create XML. Here’s an example:

xml = XMLBuilder.new
xml.document :type => 'xml', :use => 'example' do |document|
  document.description { |desc| desc.add "This is an example of using XMLBuilder.\n" }
  document.nextmeeting :date => Time.now+100000 do |meeting|
    meeting.agenda { |agenda| agenda.add "Nothing of importance will be decided.\n" }
    meeting.clearance true, :level => :classified # Passing true in as the first parameter will cause it to be a tag with no closing tag.
  end
  xml.add "I hope that this has been a good example."
end
p xml.str
# <document type="xml" use="example">
# <description>
# This is an example of using XMLBuilder.
# </description>
# <nextmeeting date="2017-02-10 21:56:56 -0800">
# <agenda>
# Nothing of importance will be decided.
# </agenda>
# <clearance level="classified" />
# </nextmeeting>
# I hope that this has been a good example.
# </document>

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeXMLBuilder

XMLBuilder#initialize simply sets the stored string to “”.



28
29
30
# File 'lib/xmlbuilder.rb', line 28

def initialize
  @str = ""
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object Also known as: add_element

XMLBuilder#method_missing.



44
45
46
47
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
# File 'lib/xmlbuilder.rb', line 44

def method_missing(name, *args, &block)
  if args.length == 2
    one_tag, hash = *args
  elsif args.length == 1
    if args[0].is_a? Hash
      one_tag, hash = *[false, args[0]]
    else
      one_tag, hash = *[args[0], {}]
    end
  else
    one_tag, hash = false, {}
  end
  @str << "<#{name}"
  if one_tag
    hash.each do |k, v|
      @str << " #{k}=\"#{v}\""
    end
    @str << " />\n"
  else
    hash.each do |k, v|
      @str << " #{k}=\"#{v}\""
    end
    @str << ">\n"
    if block
      block.call(self)
    end
    @str << "</#{name}>\n"
  end
  return @str
end

Instance Attribute Details

#strObject (readonly) Also known as: to_s, to_str, inspect

Returns the value of attribute str.



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

def str
  @str
end

Instance Method Details

#add(str) ⇒ Object

XMLBuilder#add adds a string (with no processing) to the object’s string.



36
37
38
# File 'lib/xmlbuilder.rb', line 36

def add(str)
  @str << str
end

#clearObject

XMLBuilder#clear does the same thing as #initialize (by delegating to it).



32
33
34
# File 'lib/xmlbuilder.rb', line 32

def clear
  initialize # That's essentially what it does.

end