Ruby Fu

Secrets of a Ruby Ninja for your edification and amusement.

Wednesday, May 16, 2007

 

super is super

The super keyword is pretty sweet. It remembers the context under which it was used, even when you call an alias of the containing method. Example:
class X
def method
"got it"
end
end
class Y < X
def method
"#{super}!"
end
end
class Z < Y
alias_method :original_method, :method
def method
"you #{original_method}"
end
end

X.new.method # <= "got it"
Y.new.method # <= "got it!"
Z.new.method # <= "you got it!"

This behavior gives alias_method real flexibility when used to modify behaviors by composing method chains to pre-defined methods. I was first surprised by this behavior, but it was a pleasant surprise as it meant I didn't have to worry about 'super' suddenly referring to something else when delegating to aliased methods.

Labels: , , , ,


posted by Brendan Baldwin  # 12:19 PM   0 Comments   Links to this post

Archives

May 2007   June 2007  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]