How To Monkey Patch A Class In Ruby

Posted by Weston Ganger on April 05, 2016

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

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:

Posted in Rails and Tagged with ruby 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts