How To Monkey Patch A Class In Ruby

Posted by Weston Ganger

Sometimes you may need to override a method or add a new one to an existing class from a library or gem using a monkey patch.

I did this in an initializer and uses a snazzy method called class_eval.


MyClass.class_eval do
  def do_work
    #do work
  end
end

If you did not use class_eval you can run into errors where your patch creates a new class instead of overriding. This just makes your monkey patches much more sure-fire.


Related External Links:

Article Topic:Software Development - Rails

Date:April 05, 2016

Recommended Posts