How to save ruby builder generated xml instead of rendering it in rails application?

tom eustace picture tom eustace · Dec 22, 2010 · Viewed 9.4k times · Source

I have a builder that renders xml when create is called. How can I skip the rendering step, but save the xml to the filesystem?

def create
    @server = Server.new(params[:server])

    respond_to do |format|
        if @server.save
            flash[:notice] = "Successfully created server."
            format.xml
        else
            render :action => 'new'
        end  
    end
end

Answer

Daniel Rikowski picture Daniel Rikowski · Dec 22, 2010

The XML builder can write its data to any object supporting the << operator. In your case String and File objects seem to be the most interesting.

Using a string would look something like this:

xml = Builder::XmlMarkup.new  # Uses the default string target
# TODO: Add your tags
xml_data = xml.target!  # Returns the implictly created string target object

file = File.new("my_xml_data_file.xml", "wb")
file.write(xml_data)
file.close

But since the File class supports the << operator as well, you can write the data directly into a file:

file = File.new("my_xml_data_file.xml", "wb")
xml = Builder::XmlMarkup.new target: file
# TODO: Add your tags
file.close

For further details have a look at the documentation of XmlMarkup.