Rails

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
  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:


Posted in Rails and Tagged with ruby 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts