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

Marko co-founded Rendered Text. He’s a programmer with a passion of creating something for other people, coupled with interests in how things work in the society and nature. He is having a great time working across many areas in the company, including product design, helping the engineering teams, empowering users and marketing. He likes to counterbalance it all with running, cycling or a day in the woods.

Suggested Reads

Inject is a fundamental building block

Inject is one of the fundamental, and most versatile constructs available in functional languages. It can be used to implement map, select, max, all? and a bunch of other iteration related methods. Unfortunately, many programmers are not aware of its awesome powers. This article is here to improve this fact.

Contact

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.

Rendered Text
Svetozara Miletica 10
21000 Novi Sad
Serbia