Calling the original instance method after overriding in Ruby
Say, there is a class:
class Base
def test
"original result"
end
end
And a descendant that overrides base class method:
class Descendant < Base
def test
"overridden result"
end
end
How to call Base#test
in the Descendant
instance context, outside from the Descendant#test
? In other words, how woud you access super
for some secific instance method outside from the override?
There is a way:
class Descendant < Base
def test
"overridden result"
end
def original_test
super_test = Base.instance_method(:test).bind(self)
super_test.call
end
end
Descendant#original_test
will call the Base#test
:
Descendant.new.original_test
# => "original result"
Same approach works for module methods: ImportedModule.instance_method(:method_name).bind(self).call
Somewhat related: