Notes on 2009/10/16 - overriding to_xml, alias chaining and more

Let’s say you want to augment a model’s default XML output by just a tag or two which do not directly come from its attributes. It’s quite easy once you realize that to_xml optionally takes a block, so that you can append tags by doing something like:

event.to_xml do |xml|
  xml.location do
    xml.name event.location.name
    xml.city event.location.city
  end
end

However this requires that you to replace render :xml => @events in your controller with something more complex. Using alias chaining you can extend the default behaviour of to_xml in your model and keep the controller code the same.

Alias chaining is a way to dynamically modify methods in Ruby. First you create an alias for the method to be modified. This alias provides a name for the unmodified version of the method which you can use. Next you define a new version of the method, which calls the unmodified version through the alias. Of course, it can also add whatever functionality is needed before and after it does that. For example:

class Event < ActiveRecord::Base

  belongs_to :location

  alias original_to_xml to_xml

  def to_xml(options = {})
    original_to_xml(options) do |xml|
      xml.location do
        xml.name event.location.name
        xml.city event.location.city
      end
    end
  end
end

On a side note, don’t fix other people’s failing tests if you’re hungry.

Comments powered by Disqus