Marko Anastasov wrote this on October 16, 2009

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

About Marko Anastasov

Rendered Text co-founder. Started with code, currently more focused on people and words. Foosball striker and entry-level cyclist.

Suggested Reads

Rails Testing Handbook

A new ebook on building test-driven Rails apps with RSpec and Cucumber.

At Rendered Text, we have a long history with Ruby on Rails. Checking the blog archive reminds me that we published first posts about working with Rails way back in 2009.

———

Rendered Text is a software company. For questions regarding Semaphore, please visit semaphoreci.com. Otherwise, feel free to get in touch any time by sending us an email.