红宝石会发生冲突吗?

发布于 2024-09-11 09:10:16 字数 92 浏览 7 评论 0 原文

作为红宝石新手,我想知道宝石之间是否会发生冲突?例如,如果 2 颗宝石覆盖了 <<数组上的方法,哪个会获胜,或者有什么东西可以阻止这个?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滥情空心 2024-09-18 09:10:16

我认为您正在谈论重新定义方法,而不是覆盖它们,对吗?如果两个库在两个不同的子类中重写相同的方法,就不会有任何问题。

如果两个或多个库重新定义相同的方法,则最后加载的库获胜。事实上,这实际上与一个库重新定义方法没有什么不同: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.

回心转意 2024-09-18 09:10:16

据我所知,您正在谈论猴子补丁(在红宝石社区中也称为鸭子打孔)。

这篇文章有另一个猴子补丁(和其他做法)变坏的例子。

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.

陈独秀 2024-09-18 09:10:16

实际上,不会,但如果你真的尝试过,你可能会构建出这样的情况。这是一篇有趣的文章(虽然旧)解释了怎么会发生这种事。

如果两个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文