I just had this idea and thought I’d share it in case someone can
upon it, make it more robust. Basically, I’ve run into a situation a few
times where I want to override methods in a class but retain access to
implementations, the sort of thing people like to use alias_method_chain
for. I tend to favour this approach, though:
meth = instance_method(:foo)
define_method(:foo) do |some, args|
result = meth.bind(self).call(some, args)
# do extra stuff…
But, then you’ve lost the old implementation: it’s hidden in the closure
you can’t get another reference to it from anywhere else. So, I’ve come
with a way in which you can copy the class’s methods into a module,
that module (making it part of the inheritance chain) and then mix other
modules in. Later modules can thereby override the class’s own methods
use ‘super’ to refer to them. This lets you insert code between an
class and all its subclasses, which can be useful.
Code on github, with an example:
Comments, suggestions, and accusations of idiocy all very much welcome.
Expanding from this, I’d like to figure out how I can insert modules at
arbitrary points in the inheritance chain, rather than just using
to come between a module and it’s last included module.
+44 (0) 7771512510