Only call super when possible
Today we were faced with an interesting question in #ruby-lang:
<Judofyr> is there a way to find out if it’s safe to call “super”? <Judofyr&> aka. it’s defined on the superclass
After some ugly solutions (like self.class.ancestors.any? and super rescue nil
) apeiros came up with a nicer one:
<apeiros_> super if defined? super
Example:
class Test
def foo
1
end
end
class Test2 < Test
def foo; super if defined? super; end
def bar; super if defined? super; end
end
t = Test2.new
t.foo # => 1
t.bar # => nil