Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you do a safe, backwards-compatible "reverse-monkeypatch" in Ruby?

If your coworker "opens" ("monkeypatches") a class in Ruby and redefines some important functionality that you need to use, how do you access that original pre-monkeypatched functionality without breaking a system that already relies/has dependencies on his monkeypatched definitions?

like image 387
pez_dispenser Avatar asked Feb 28 '23 17:02

pez_dispenser


2 Answers

Given the example of the method overriding, if you can get some code loaded before his monkey patch is loaded then you can alias the method.

class Fixnum
  alias_method :original_plus, :+
end

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

>> 5 + 3
=> 2
>> 5.original_plus(3)
=> 8
like image 60
Ian Terrell Avatar answered Apr 07 '23 01:04

Ian Terrell


I recently saw this in the rubyflow feed - its a simple library that lets you namespace top level constants called aikidoka. Without any details of how/what is being monkey patched it is a bit tough to help. In theory though you could use an approach like this to namespace the monkey-patched version of the class so that you can access both it and the original independently.

like image 36
paulthenerd Avatar answered Apr 07 '23 02:04

paulthenerd