Sunday, February 21, 2010

How to use XML Builder templates in Rails (I)

For an application I had to generate a customized XML view in a Rails application. As it is known, Rails comes with the Builder gem that is a tool to render XML files from templates. Documentation of this gem can be found in Rubyforge or in Ruby API description.

In order to customize this xml, I used as a starting point this stackoverflow post. For this purpose I have created a simple Rails application using scaffolding (employees) with a single database table that is a list of employees with the following 4 fields: age, category, family name and given name). In order to customize the XML when the user types http://localhost:3000/employees/1.xml (for instance), do the following:
  1. Create a builder template that is called, for instance, show.builder, this template is the one that will be used to show the database entry (in my sample application it would be (http://0.0.0.0:3000/employees/1.xml). The code of this template is the following (tags are in spanish):

    xml.instruct!

    xml.employee do

    xml.nombre(@employee.given_name)
    xml.apellido(@employee.family_name)
    xml.edad(@employee.age)
    xml.categoria(@employee.category)

    end

  2. In the controller (in my case employee_controller) I had to substitute the line

    format.xml { render :xml => @employee }

    by the line

    format.xml { @employee }

    Otherwise the application will render the XML in the default mode. If you still want to keep the default XML format, you can always redirect the rendering using the routes.cb configuration file.
If in addition you want to generate the XML and send to the user (besides showing it in the browser, change the previous format line:

format.xml { @employee }

by

format.xml do
stream = render_to_string(:template=>"employees/show.builder" )
send_data(stream, :type=>"text/xml",:filename => "test.xml")
end


This way, the Rails application renders the template and places it in stream and afterwards send this data into the test.xml file.

That's it!

1 comment:

  1. Nice post ! Thanks for sharing valuable information with us. Keep sharing.. Ruby on Rails Online Course India

    ReplyDelete