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

pez*_*ser 1 ruby monkeypatching

假设您的同事monkeypat修复Fixnum类并重新定义+方法以减去而不是添加:

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

>> 5 + 3
=> 2
Run Code Online (Sandbox Code Playgroud)

您的问题是您想要访问+方法的原始功能.因此,您将此代码放入相同的源文件之前.它在将 monkeypatches 之前将+方法别名为"original_plus" .

class Fixnum
  alias_method :original_plus, :+
end

class Fixnum
  def +(x)
    self - x
  end
end
Run Code Online (Sandbox Code Playgroud)

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

>> 5 + 3
=> 2
>> 5.original_plus(3)
=> 8
Run Code Online (Sandbox Code Playgroud)

但我需要知道的是:

有没有其他方法加载这个别名BEFORE他的monkeypatch加载除了将其粘贴到他修改的相同源文件中?

我的问题有两个原因:

  1. 我可能不希望他知道我已经这样做了
  2. 如果源文件被更改以使别名最终低于monkeypatch,则别名将不再产生所需的结果.

ram*_*ion 6

当然.需要源文件之前,只需将反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
Run Code Online (Sandbox Code Playgroud)