views:

77

answers:

3

As a ruby newbie, I was wondering, will gems ever conflict with eachother? For example, if 2 gems overrode the << method on array, which would win, or is there something to stop this?

Thanks

A: 

In practice, no, though you could probably construct a situation like that if you really tried. Here's an interesting article (though old) that explains how this could happen.

If two gems "overrode the << method on array" they would need to be subclassing Array, and those classes would have different names or be in different modules.

Evan Cordell
Actually, it happens in practice as well. We had such experience of two gems redefining same methods of `Symbol` class (one being Sequel, another I can't remember right now). And no, you don't have to subclass a class in Ruby in order to redefine its methods.
Mladen Jablanović
You don't have to subclass a class to redefine methods, but you do to override them, which is what the question asked. But you're right, I misunderstood the question.
Evan Cordell
I don't think there's a difference between overriding and redefining methods in Ruby, just a naming convention - if you do it in inherited class, you're "overriding", if you do it in the class it has been defined in, you are "redefining".
Mladen Jablanović
+4  A: 

I assume you are talking about redefining methods, not overriding them, right? If two libraries overrode the same method in two different subclasses, there wouldn't be any problem.

If two or more libraries redefine the same method, then whichever one happens to be loaded last wins. In fact, this is actually no different than just one library redefining a method: the Ruby interpreter provides an implementation of Array#<< for you, and if you redefine it, your definition wins, simply because it came later.

The best way to stop this is simple: don't run around screwing with existing methods. And don't use libraries that do. The -w commandline flag to enable warnings is very helpful there, since at least in Ruby 1.9.2 it prints a warning if methods get redefined.

In Ruby 2.0, there will probably be some kind of mechanism to isolate method (re-)definitions into some kind of namespace. I wouldn't hold my breath, though: these so-called selector namespaces have been talked about in the Ruby community for almost 10 years now, and in the Smalltalk community even longer than that, and AFAIK nobody has ever produced a working implementation or even a working design for Ruby. A newer idea is the idea of Classboxes.

Jörg W Mittag
+1  A: 

As far as I can tell, you're talking about monkeypatching (also known as duck punching in the ruby community).

This article has another example of monkeypatching (and other practices) gone bad.

Andrew Grimm
Duck punching is a new one for me, heh.
Daniel Vandersluis