Ruby – Recommended approach to monkey patching a class in ruby

monkeypatchingruby

I've noticed that there are two common ways to monkey patch a class in ruby:

Define the new members on the class like so:

class Array
   def new_method
     #do stuff
   end
end

And calling class_eval on the class object:

Array.class_eval do
   def new_method
      #do stuff
   end
end

I'm wondering if there is any difference between the two and whether there are advantages to using one approach over the other?

Best Answer

Honestly, I used to use the 1st form (reopening the class), as it feels more natural, but your question forced me to do some research on the subject and here's the result.

The problem with reopening the class is that it'll silently define a new class if the original one, that you intended to reopen, for some reason wasn't defined at the moment. The result might be different:

  1. If you don't override any methods but only add the new ones and the original implementation is defined (e.g., file, where the class is originally defined is loaded) later everything will be ok.

  2. If you redefine some methods and the original is loaded later your methods will be overridden back with their original versions.

  3. The most interesting case is when you use standard autoloading or some fancy reloading mechanism (like the one used in Rails) to load/reload classes. Some of these solutions rely on const_missing that is called when you reference undefined constant. In that case autoloading mechanism tries to find undefined class' definition and load it. But if you're defining class on your own (while you intended to reopen already defined one) it won't be 'missing' any longer and the original might be never loaded at all as the autoloading mechanism won't be triggered.

On the other hand, if you use class_eval you'll be instantly notified if the class is not defined at the moment. In addition, as you're referencing the class when you call its class_eval method, any autoloading mechanism will have a chance to locate class' definition and load it.

Having that in mind class_eval seems to be a better approach. Though, I'd be happy to hear some other opinion.