Rails to_xml with procs

Ever wanted to add something to the xml representation of an ActiveRecord object that wasn’t a method or an include? You can with procs.

respond_to do |format|
  format.xml do
    proc = Proc.new { |options| options[:builder].tag!('saved', current_user.saved?(@page)) }
    render :xml => @page.to_xml(:include => [:user], :procs => [proc])
  end
end

And now this will spit out:

<?xml version="1.0" encoding="UTF-8"?>
<page>
  <content>So here's line 1</content>
  <created-at type="datetime">2009-10-15T16:50:57Z</created-at>
  <dictionary-id type="integer">1</dictionary-id>
  <saved>false</saved>
</page>

In this case, the model doesn’t know anything about the user and I wanted to keep it that way, but the XML api call needs to include the saved state.


Related Posts

  1. Rails Fragment Caching With Multiple Accounts
  2. iPhone/iPad UISearchBar and UISearchDisplayController Asynchronous Example
  3. Vim ack plugin with MacVim and MacPorts
  4. SPF Records with Rails and ActionMailer
  5. Google Analytics API with Ruby
You should follow me on Twitter: @patrickxb