How to Monkey-Patch a core Class in Ruby on Rails

Recently while working on a project I found myself using .delete! to remove double quotes quite often. The way the project is setup there are places where double quotes are required and some places where they need to be removed. After I found myself using .delete!("\"") a good bit I decided it to put it in a helper method.

def remove_quotes(string)


But then I found myself needing to use it in a model and since helpers aren't meant to used in that way I needed a new solution. After discussing it with a co-worker, I decided to monkey-patch the String class and create my own method for removing double quotes.

Step 1

All the code will be stored in the lib directory, so one of the first steps is to organize the folders and files. Since I was creating a monkey-patch for the String class, a core class, I first created a folder called core_ext. Giving it this name will help keep your code organized and also help anyone looking at the code base in the future understand what is going on. Inside core_ext I created a file called string.rb, this will contain the new string method.

Step 2

Now simply write the new method you wish to implement like so:

String.class_eval do

def delete_quotes!

def delete_quotes

To keep with convention I created two methods, one with ! and one without. The difference of course being that the ! method will modify the string where as the one without will return a new string.

Step 3

The final step is to setup an initializer to load the new files containing our monkey-patch. Since this initializer is loading lib files I named my file `lib_loader.rb`, once created include the follow code.

require "#{Rails.root}/lib/core_ext/string"

Now you should be able to call your new method anywhere in your project.


May. 20 2015