A New Alternative to Monkeypatching

chromatic on 2008-04-02T23:00:17

I thought I’d share a technique that I’ve known about for some time, but seems to not have gotten into the normal ruby vernacular.

This trick is the use of super in methods contained in a Module.

Evan Phoenix, super is your friend

This post was a day late, right?

Update: added the rest of the punchline sentence.


I, uhm…

Aristotle on 2008-04-03T09:31:43

… wow.

Context

djberg96 on 2008-04-03T15:22:48

That's not very nice, cutting out the rest of the sentence like that. Here it is for your faithful readers:

This trick is the use of super in methods contained in a Module.
His point being that most Ruby users don't think to use super in a module, since OO literature tends to condition you to think of it in the context of classes only. I've no idea if super is legal in a Java interface, for example.

When folks start blogging about techniques with super and traits as if it's something special, I'll be sure to reference this post.

Re:Context

Aristotle on 2008-04-03T16:50:11

Except you won’t, because Perl 6 has multiple inheritance, so for correctness it will have to be “next”, not “super”… which is something we already do in Perl 5 (and for the same reason). So it’s going to be business as usual in v6.

Re:Context

chromatic on 2008-04-03T16:58:34

His point being that most Ruby users don't think to use super in a module...

Why would they think to use methods in a module then?

OO literature tends to condition you to think of it in the context of classes only.

That's irrelevant. Plenty of OO literature tends to condition people to think of polymorphism in terms of inheritance only. Plenty of OO literature is bad. Besides, little extant OO literature recommends monkeypatching (or my favorite euphemism for monkeypatching, punching grandma up the stairs), and plenty of Ruby programmers do that.

That all presumes that Ruby programmers tend to read OO literature. In my experience, most programmers of any language don't read the literature.

I've no idea if super is legal in a Java interface, for example.

Why does that matter? We're talking about Ruby.

To avoid the almost inevitable followup charges of extreme jealousy, hypocrisy, and crippling incontinence, I will admit that the behavior Evan describes does not work properly in Perl 5. (That's why I maintain Simon Cozens's SUPER.)