To Trick 'to_xml'

December 14th, 2007

XML Knowledge!

Recently, I’ve been sprinkling more and more XML into my projects. There’s a terrific helper method in Rails dubbed to_xml, which you can run over a collection of records.

At first, I had trouble using this because I was limited to outputting every typical AR attribute for the given model. (ie. I’d receive , , , etc. XML tags) After a bit of digging I found some options for to_xml which provides you with control over which attributes it XML’izes.

Here they are in action:

xml_controller.rhtml (Controller)

1
2
3
4
5
6
7
8
9
def compile_slides
  @slides = Slide.find( :all )
  
  # The :only call is necessary to omit all of the typical attributes
  render( :xml => @slides.to_xml(
    :only => [],
    :methods => [ :name, :cover_photo_url, :xml_url ]
  ) )
end

The :only option is overriding the to_xml’s default behaviour of spitting out every attribute, while :methods is stating which custom methods for the AR Model I want to include. For instance, instances of Slide repond to a method named ‘xml_url’:

slide.rb (Model)

1
2
3
4
5
6
7
def xml_url
  return "" if self.url.blank?
  return "http://#{self.url}" unless self.url[/http\:\/\//]
  return self.url
end

...

This will give us something like:

slides.xml (XML)

1
2
3
4
5
<slide>
  <xml-link>
    /articles/1-how-to-search-google
  </xml-link>
</slide>

Flexible!

Sorry, comments are closed for this article.