How can you influence the sequence of loading Ruby code?

Suppose your monkey colleague visits the Fixnum class and overrides the + method for subtraction instead of add:

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

>> 5 + 3
=> 2

      

Your problem is that you want to access the original functions of the + method. This way you remove this code before it in the same source file. It will redirect the + method to "original_plus" before it promises it.

class Fixnum
  alias_method :original_plus, :+
end

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

      

You can now access the original functions of the + method via original_plus

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

      

But I need to know the following:

Is there any other way to load this alias before it loads with monkeypatch, other than inserting it into the same original file that it modified?

There are two reasons for my question:

  • I don't want him to know that I did it.
  • If the source file is modified such that the alias ends with BELOW the monkeypatch, then the alias will no longer give the desired result.
+1


a source to share


2 answers


Sure. Just insert anti-monkeypatch into your code before the source file is needed.



 % 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

      

+6


a source


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



Seriously, you should talk to your colleague.

If, for example, in your example, he has overridden an existing method in order to change its behavior, you should talk to him and advise him to use alias_method_chain

in order to preserve the existing behavior.

+2


a source







All Articles