views:

121

answers:

2

I have started using xml builder templates for most of my model. I need to find a generic way to build XML outside of a render which uses the .xml.builder template instead of the generic .to_xml method provided in the model

I gather that I will have to override the default to_xml (or add a to_my_xml), but I am unable to see how to get XMLBuilder to use my .builder files.

Any ideas?

+1  A: 

Add a respond_to block in your controller so that the appropriate template is rendered according to the requested format. For example:

def show
  ...
  respond_to do |format|
    format.html # renders show.html.erb
    format.xml  # renders show.xml.builder
  end
end
John Topley
Thanks for the quick response. I already have a respond block, but need to know the XML that will be generated by the respond_to block before it runs as I need to pass this XML as an XMPP message. The render in the respond_to block uses a .xml.builder template which I am trying to mimic.
Barrie
A: 

If you are looking for how to create xml using builder then this is how you can do it

require 'rubygems'
require 'builder'
builder = Builder::XmlMarkup.new(:indent=>2)
builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
builder.my_elements do |e|
  builder.myitem {|element| element.my_element_name('element_value')}
end

#=>

<?xml version="1.0" encoding="UTF-8"?>
<my_elements>
  <myitem>
    <my_element_name>element_value</my_element_name>
  </myitem>
</my_elements>
nas
Hi Naz - thanks for the that.The key thing though is that I want to use the same template file that render uses to generate the XML.So, my respond_to block looks like this:respond_to do |format| format.html format.xml { render :template => "slides/slides_and_comments.xml.builder"}endHow do I get XmlBuilder to use the "slides/slides_and_comments.xml.builder" template?
Barrie