Wednesday, April 9, 2008

Tweaking XML Rendering For ActiveScaffold

Another day, another few hours of googling Ruby blogs to figure out how to accomplish some seemingly trivial task. This time it's making some minor adjustments to the XML rendering of an ActiveRecord model when the controller is being supplied by ActiveScaffold. Don't get me wrong, I love automagically created applications. It's just that, sometimes, all you want to do is change... this one... freaking detail...

API says you can pass options to to_xml. As in:

my_model.to_xml :except => [:ugly_field]

Problem is, the to_xml method is getting called by the ActiveScaffold ApplicationController and you don't really want to edit that. If you just want to make a small adjustment and not rewrite the entire rendering method the best option you have is to overload this method in the model class, add the options to the passed array and call super()

def to_xml(options={})
  options[:methods] = [:get_formatted_value, :other_value]
  options[:except] = [:irrelevant_accession_number]
  super(options)
end

Should have been obvious, I suppose, but I spent some of my (dwindling) wattage on it. Oh well, here's hoping the next rubie finds this on a google search for "activescaffold xml rendering."