blah blah woof woof

Setting default arguments for to_xml for your ActiveRecord model

Tim Riley 2008.04.11

Rails provides you with a lot of scope for customising the XML serialisation of models with to_xml. Among other things, you can exclude attributes, include objects that are first-level associations, and include the results of any custom methods for your model.

However, most of the examples for these only show this customisation taking place in the scope of the controller, where the arguments are passed to a single call of to_xml. This is not very DRY if you want to customise the default to_xml output for your model to include or exclude some information.

Customising the default behaviour is pretty easy. Say I have an extra method inside a model that combines price and tax to formulate a net price, and I want this to be included in the XML serialisation every time. Here is what to do:

class Product < ActiveRecord::Base
  def net_price
    self.price + self.tax
  end

  alias_method :ar_to_xml, :to_xml
  
  def to_xml(options = {}, &block)
    default_options = { :methods => [ :net_price ]}
    self.ar_to_xml(options.merge(default_options), &block)
  end
end

Want More?

Previous Article

  1. 2008.04.10 Enabling the "Develop" menu in Safari

Next Article

  1. 2008.04.12 Activating the screensaver with Quicksilver in OS X

Archived Comments

mrflip 2008-08-20 20:11

should that be reverse_merge, or default_options.merge(options) ?

david 2008-11-05 13:40

Another great, simple way to do this is the attr_serializable plugin. It lets you set a whitelist of attributes in a single line that you want to be used in to_xml and to_json.