如何影响 Ruby 代码的加载顺序?

发布于 2024-07-20 16:49:12 字数 703 浏览 3 评论 0原文

假设您的同事对 Fixnum 类进行了猴子修补,并重新定义了 + 方法以进行减法而不是加法:

class Fixnum
  def +(x)
    self - x
  end
end

>> 5 + 3
=> 2

您的问题是您想要访问 + 方法的原始功能。 因此,您可以将此代码放在同一个源文件中的代码之前。 在猴子修补之前,它会将 + 方法别名为“original_plus”。

class Fixnum
  alias_method :original_plus, :+
end

class Fixnum
  def +(x)
    self - x
  end
end

现在你可以通过original_plus访问+方法的原始功能,

>> 5 + 3
=> 2
>> 5.original_plus(3)
=> 8

但我需要知道的是:

除了将其粘贴到他修改的同一源文件中之外,还有其他方法可以在他的monkeypatch加载之前加载此别名吗?

我的问题有两个原因:

  1. 我可能不想让他知道我已经这样做了
  2. 如果源文件被更改,使得别名最终位于猴子补丁下方,那么别名将不再产生所需的结果。

Let's say your coworker monkeypatches the Fixnum class and redefines the + method to subtract instead of add:

class Fixnum
  def +(x)
    self - x
  end
end

>> 5 + 3
=> 2

Your problem is you want to access the original functionality of the + method. So you drop this code in before his in the same source file. It aliases the + method to "original_plus" before he monkeypatches it.

class Fixnum
  alias_method :original_plus, :+
end

class Fixnum
  def +(x)
    self - x
  end
end

Now you can access the original functionality of the + method through original_plus

>> 5 + 3
=> 2
>> 5.original_plus(3)
=> 8

But what I need to know is this:

Is there any other way of loading this alias BEFORE his monkeypatch loads besides sticking it into the same source file that he modified?

There are two reasons for my question:

  1. I may not want him to know that I have done this
  2. If the source file is altered so that the alias ends up BELOW the monkeypatch, then the alias will no longer produce the desired result.

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

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

发布评论

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

评论(2

静待花开 2024-07-27 16:49:12

当然。 只需在您需要其源文件之前将 anti-monkeypatch 粘贴到您的代码中即可。

 % cat monkeypatch.rb
 class Fixnum
   def +(x)
     self - x
   end
 end
 % cat mycode.rb
 class Fixnum
   alias_method :original_plus, :+
 end
 require 'monkeypatch'
 puts 5 + 3 #=> 2
 puts 5.original_plus(3) #=> 8

Sure. Just stick the anti-monkeypatch in your code before you require his source file.

 % cat monkeypatch.rb
 class Fixnum
   def +(x)
     self - x
   end
 end
 % cat mycode.rb
 class Fixnum
   alias_method :original_plus, :+
 end
 require 'monkeypatch'
 puts 5 + 3 #=> 2
 puts 5.original_plus(3) #=> 8
心的憧憬 2024-07-27 16:49:12

Monkeypatching 很适合扩展现有类并添加新功能。 通过猴子补丁来改变现有功能的行为真是太疯狂了!

说实话,你应该和你的同事谈谈。

如果像您的示例一样,他确实重新定义了现有方法只是为了更改其行为,您应该与他交谈并建议他使用 alias_method_chain 来保存现有行为。

Monkeypatching is nice to extend an existing class and add new features. Monkeypatching to change the behavior of existing features is just crazy!

Seriously, you should talk with your coworker.

If like in your example, he did redefine an existing method just to change its behavior, you should talk to him and advise him to use alias_method_chain in order to save the existing behavior.

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