红宝石会发生冲突吗?
作为红宝石新手,我想知道宝石之间是否会发生冲突?例如,如果 2 颗宝石覆盖了 <<数组上的方法,哪个会获胜,或者有什么东西可以阻止这个?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
作为红宝石新手,我想知道宝石之间是否会发生冲突?例如,如果 2 颗宝石覆盖了 <<数组上的方法,哪个会获胜,或者有什么东西可以阻止这个?
谢谢
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
我认为您正在谈论重新定义方法,而不是覆盖它们,对吗?如果两个库在两个不同的子类中重写相同的方法,就不会有任何问题。
如果两个或多个库重新定义相同的方法,则最后加载的库获胜。事实上,这实际上与一个库重新定义方法没有什么不同:Ruby解释器为您提供了
Array#<<
的实现,并且如果您重新定义它,你的定义获胜,仅仅因为它来得晚。阻止这种情况的最好方法很简单:不要乱用现有的方法。并且不要使用这样做的库。启用警告的
-w
命令行标志非常有用,因为至少在 Ruby 1.9.2 中,如果重新定义方法,它会打印警告。在 Ruby 2.0 中,可能会有某种机制将方法(重新)定义隔离到某种命名空间中。不过,我不会屏住呼吸:这些所谓的 选择器命名空间在 Ruby 社区中已经讨论了近 10 年,在 Smalltalk 社区中讨论的时间甚至更长,而且据我所知,还没有人产生过有效的实现甚至是 Ruby 的工作设计。一个较新的想法是Classboxes。
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.
据我所知,您正在谈论猴子补丁(在红宝石社区中也称为鸭子打孔)。
这篇文章有另一个猴子补丁(和其他做法)变坏的例子。
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.
实际上,不会,但如果你真的尝试过,你可能会构建出这样的情况。这是一篇有趣的文章(虽然旧)解释了怎么会发生这种事。
如果两个 gem“覆盖数组上的 << 方法”,它们将需要对 Array 进行子类化,并且这些类将具有不同的名称或位于不同的模块中。
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.