How to save created ruby ​​builder instead of xml instead of rendering in rails application?

I have a builder that displays xml when create is called. How to skip the rendering step but save xml in the file system?

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 
+7
source share
2 answers

The XML constructor can write its data to any object that supports the << operator. In your case, the 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 also supports the << operator, you can write data directly to the file:

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

See the XmlMarkup documentation for more information.

+26
source

It is so good. You can also create a path to store all xmls in this folder so that the application is organized.

 file = File.new("some_path/my_xml_data_file.xml", "w") 

Thanks Daniel

0
source

All Articles