How to generate an XML file using Ruby and Builder :: XMLMarkup Templates?

As you all know, with Rails you can use the Builder :: XMLMarkup templates to provide an HTTP response in XML format instead of HTML (using the response_to command). My problem is that I would like to use the Builder :: XMLMarkup template system, not Rails, but only with Ruby (that is, a standalone program that generates / outputs an XML file from an XML template). The question then is twofold:

  • How do I tell the Ruby program, which is the template I want to use? and
  • How to specify the Builder class, which is the output XML file?

There is already a similar answer in Stackoverflow ( How can I generate XML from XMLBuilder using the .xml.builder file? ), But I'm afraid this only applies to Rails.

+3
source share
2 answers

Ever read RDocs Builder? github.com

Okay, see if I can help a bit. Here is a very far-fetched example.

require 'builder'

@received_data = {:books => [{ :author => "John Doe", :title => "Doeisms" }, { :author => "Jane Doe", :title => "Doeisms II" }]}
@output = ""
xml = Builder::XmlMarkup.new(:target => @output, :indent => 1)

xml.instruct!
xml.books do
  @received_data[:books].each do |book|
    xml.book do
      xml.title book[:title]
      xml.author book[:author]
    end
  end
end

The @output object will contain the xml markup:

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>Doeisms</title>
  <author>John Doe</author>
 </book>
 <book>
  <title>Doeisms II</title>
  <author>Jane Doe</author>
 </book>
</books>

To select a specific template, you can pass arguments to your program for this solution.
In any case, I prefer to use libxml-ruby to parse and create XML documents, but that is a matter of taste.

+7
source

I used Tilt to do (the first part) of this. It is very easy:

require 'builder'
require 'tilt'
template = Tilt.new('templates/foo.builder')
output = template.render

This will give you a string representation of your xml. At this point, you can burn it to disk.

+1
source

Source: https://habr.com/ru/post/1731985/


All Articles