Skip to content

Instantly share code, notes, and snippets.

@tisba
Last active December 12, 2015 08:08
Show Gist options
  • Select an option

  • Save tisba/4741579 to your computer and use it in GitHub Desktop.

Select an option

Save tisba/4741579 to your computer and use it in GitHub Desktop.
require "nokogiri"
some_data = nil
builder = Nokogiri::XML::Builder.new encoding: "UTF-8" do |xml|
xml.root do
# insert <options> first, and keep
# a reference to this node
options_node = xml.options
# build more XML and do stuff here AND collect some data
xml.some_node do
some_data = ["foo", "bar"]
end
# use data here, to create child nodes on
# "options"
# Without the ".foo" I just get a method missing error:
# undefined method `options_node' for main:Object (NoMethodError)
options_node.foo do |bar|
some_data.each do |data|
bar.child attr: data
end
end
end
end
puts builder.to_xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<options>
<child attr="foo"/>
<child attr="bar"/>
</options>
<some_node/>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<options class="foo">
<child attr="foo"/>
<child attr="bar"/>
</options>
<some_node/>
</root>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment