super is awesome

June 7th, 2007

First of all, sorry for the lack of posting lately. I do have lots of goodies, it’s just been a bit crazy lately. I have transitioned from 9-5 desk job, to a chaotic and uncertain freelance-ish position. And yeah, it’s been a little nuts.

Anyways, on to some ruby goodness.

I am going to give a small example of how awesome the super method is. In case you don’t know super is a special method that executes the parent method of the same name. Confused? Try this simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Foo
def bar
    'Bar!'
  end
end
foo = Foo.new
foo.bar # => 'Bar!'

class Foo2 < Foo
  def bar
    "This method says: " + super
  end
end
foo2 = Foo2.new
foo2.bar # => 'This method says: Bar!'

When foo2 calls bar it calls super witch executes the method in the parent class with the same name. This lets us append something to the returned value without have any idea what it is.

Now for a cool example with a modified Builder::XmlMarkup class.

I recently had a need to generate a lot of namespaced xml. And all elements in this xml had the same namespace. I found myself doing this over and over:

1
2
3
4
xml = Builder::XmlMarkup.new
xml.foo(:bar) {
  xml.foo(:baz)
}

which would generate

1
2
3
<foo:bar>
  <foo:baz>
</foo:bar>

I got really tired of xml.foo over and over again to create every element, so I decided to create a new XML Builder class. It looks like this:

1
2
3
4
5
class MyXmlBuilder < Builder::XmlMarkup
  def method_missing(method, *args)
    super(:foo, method, *args)
  end
end

Builder works on method_missing. Every method it doesn’t recognize gets turned into an xml tag via Builder’s method_missing method. It gets the name of the method that was called, and any args passed in as well.

We call super with the arguments we need to declare our namespace. We really wanted to call the foo method on our builder to start the namespace, and then pass it a symbol for the name of the tag, in this case passed in by the method argument.

The result is a super clean API that works just like the original Builder class, except that our namespace is automagically applied for us.

1
2
3
4
xml = MyXmlBuilder.new
xml.bar {
  xml.baz
}

Generates:

1
2
3
<foo:bar>
  <foo:baz>
</foo:bar>

super is a super valuable thing to wrap your head around. It really allows you to do some complex tasks with the smallest amount of code by leveraging existing code through truly elegant means.

I love it.

1 Response to “super is awesome”

  1. srini Says:

    good one!!!

Leave a Reply