top of page

Monkey Patching

When I was refactoring our Week 3 project, I was very motivated to create the DRY-est and most beautiful code there ever was.

Scrolling through a seemingly never-ending method I spotted a potential candidate that I could separate out. These lines were checking if the user input coming from the console fit into a specific date range:

In my vision I would simply call .valid? on a date and it would give me my boolean. My dream looked something like this:

Clearly, I was trying to imitate the concise built in methods like empty? or nil?

To dream even further, this would give me the ability to write clean conditionals like this:

So I coded away:

To make sure it worked, I ran it through irb and all looked good:

Excited like a child on Christmas morning I ran the CLI app...

Fail!

Undefined? Why? It was not a scope problem, the method was defined in the same class where it was used. I even moved it within the same method just to see if it would change anything.

The answer lies in the last part of the error message: String (NoMethodError).

For my dream to work I would have to modify the String class itself via monkey patching:

Monkey-patching is the technique of re-opening existing classes to change or add to their behavior.

I'd have to do it like this:

However, monkey patching should only be used cautiously and when really necessary. One of the pitfalls is that for anyone not aware of the monkey patches the discrepancy between the original and modified code can cause unpredicted and confusing behaviors.

The alternative solution was to modify my method to take in the user input as a parameter, in a good-old fashion.

This allows me to still have concise code, not exactly as I had dreamed of but very close:

You Might Also Like:
bottom of page