This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: A More Flexible to_xml
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
The to_xml method on your ActiveRecord classes has a bunch ���o options that let you refine how you want your models to be serialized to xml. You���ve got your :only and :except options which let you filter in/out certain attributes:
(Want to have the result of methods serialized along side member attributes? Take a look at the :methods option).
You can also include first-level associations with :include:
123456789
user.to_xml(:except => [:id, :created_at], :include => :posts)#=># <user># <name>Ryan</name># <email>ryan@spamme.com</email># <posts># <post><title>What's New in Edge Rails</title></post># </posts># </user>
You can also manipulate the XML builder directly as to_xml now yields the builder, allowing you to add arbitrary elements to the resulting serialized XML representation:
Note that the xml builder received in the block already contains the standard constructed XML representation ��� but you can now add to that with custom elements and other constructs. Just another easy way to massage the serialization to suit your needs.