HerokuRichard SchneemanExplainer
Debugging Super Methods with Ruby 2.2
Summary
Ruby exposes method metadata and caller-stack information, but before Ruby 2.2 it was difficult to identify the method ultimately reached by super, especially in metaprogrammed code. The example defines Dog#bark and SchneemsDog#bark, then extends an instance with DoubleBark, whose bark method calls super twice; inspecting the class hierarchy incorrectly reports Dog#bark because the module is not an ancestor of the instance's class. Ruby 2.2 adds Method#super_method, a feature proposed in request #9781 and accepted into the Ruby trunk, which returns the method Ruby will invoke for super, including the correct SchneemsDog#bark in this case. Calling source_location on that returned Method provides the location of the actual implementation and avoids the custom metaprogramming previously needed to trace it.
Context
Before Ruby 2.2, tracing the method that super would invoke was difficult when metaprogramming altered an object's method lookup. The class hierarchy could identify the wrong method because an extended module was not an ancestor of the object's class.
Approach / What changed
Ruby 2.2 introduces Method#super_method. Applied to a method object, it returns the method that Ruby will invoke when super is called, after which source_location can identify the implementation's location.
Takeaways
Method#super_method returns the method Ruby will call through super, rather than requiring callers to reconstruct the lookup path.
Extending an instance with DoubleBark can make class-based inspection report Dog#bark even though super from DoubleBark#bark refers to SchneemsDog#bark.
Calling source_location on the Method returned by super_method yields the location of the implementation that super will actually invoke.
Source and freshness
- Source
- heroku.com
- Published
- Added to Yomu
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.