Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 885
tom eustace Avatar asked Dec 22 '10 12:12

tom eustace


1 Answers

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.

like image 122
Daniel Rikowski Avatar answered Nov 15 '22 08:11

Daniel Rikowski