Skip to content

Instantly share code, notes, and snippets.

@reggieb
Last active October 11, 2019 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reggieb/bf11e47baa15af3dc4d2f8fd5dbab0a7 to your computer and use it in GitHub Desktop.
Save reggieb/bf11e47baa15af3dc4d2f8fd5dbab0a7 to your computer and use it in GitHub Desktop.
XBuilder - A simple tool to build complicated XML objects from nested components
require "active_support/core_ext"
class XBuilder
attr_reader :data, :namespace, :root
def initialize(data)
@namespace = data.delete(:_namespace)
@root = data.delete(:_root)
@data = data
end
def to_xml(options={})
hash = data.transform_keys do |key|
key = key.to_s.camelize if key.is_a?(Symbol)
key.include?(':') ? key : [namespace,key].compact.join(':')
end
options.merge!(root: root) if root
hash.to_xml(options)
end
end
@reggieb
Copy link
Author

reggieb commented Oct 11, 2019

An example of usage:

x = XBuilder.new(
      foo: 'bar'
    )

x1 =  XBuilder.new(
		    _root: 'ns2:X1',
		    another: 'one'
			)

x2 =  XBuilder.new(
		    _root: 'ns4:X2',
		    _namespace: :ns4,
		    and: 'another'
			)

x3 =  XBuilder.new(
			  _root: 'ns1:MyXML',
			  _namespace: :ns1,
		    from_now: 'ho',
		    'ThisID': 'kd',
		    'root' => 'ddd',
		    'name:spaced' => 'true',
		    root: 'sss',
		    x: x,
		    x1: x1,
		    y: x2
		  )

puts x3.to_xml

Produces:

<?xml version="1.0" encoding="UTF-8"?>
<ns1:MyXML>
  <ns1:FromNow>ho</ns1:FromNow>
  <ns1:ThisID>kd</ns1:ThisID>
  <ns1:root>ddd</ns1:root>
  <name:spaced>true</name:spaced>
  <ns1:Root>sss</ns1:Root>
  <ns1:X>
    <Foo>bar</Foo>
  </ns1:X>
  <ns2:X1>
    <Another>one</Another>
  </ns2:X1>
  <ns4:X2>
    <ns4:And>another</ns4:And>
  </ns4:X2>
</ns1:MyXML>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment