Calling Grandparents in Ruby
I’m not the first to post about this, but it’s worth re-posting since not everyone knows how to do it.
Ruby makes it easy to call an objects’ superclass methods:
class Parent
def foo
# ...
end
end
class Child < Parent
def foo
super
end
end
But what if we want to call the super-superclass method, skipping over the superclass definition? Or what if an included module has overridden the superclass method?
class Parent
def foo
# ...
end
end
module Interloper
def foo
puts "Bwahaha all your foos are belong to us!"
end
end
class Child < Parent
include Interloper
def foo
# ???
end
end
You can do it, of course (this is Ruby); but the means may not be immediately obvious:
class Child < Parent
include Interloper
def foo
Parent.instance_method(:foo).bind(self).call
end
end
If it's not clear what's going on here: we're creating an UnboundMethod object representing the Parent#foo method, binding that method to the child class instance, and immediately invoking it. It's a bit unwieldy, but when you want to be absolutely sure of which method implementation you are calling, this is the best way to go.

This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Related posts:
