1. Computing

Refinements: The End of Monkey Patching


Updated December 08, 2010

Ruby is an extremely flexible language. It's a truly object oriented language, meaning everything is an object that responds to messages. It's also an open language, meaning you can not only add new methods to any class, but replace any method in any class. This has led to something that's at once great, and terrible: monkey patching.

"Monkey patching" is the act of modifying any of the base Ruby classes to do something clever, useful, correctly or just differently. It can lead to a lot of meta-language type code, and is one of the things that makes Ruby so fun. But it's dangerous. What if you change a method that a certain gem uses? You can either outright break it, or break it in some way that's so subtle, it'll take you a week to figure it out.

So what to do about this? A proposed feature called "refinements" will attempt to fix this. A refinement is, simply put, the monkey patch as a formal language feature that you can turn on or off at will. When you want to use the monkey patch, you can say "Ruby, I'd like to use this monkey patch in the following code, but don't let any code that isn't expecting the monkey patch use it." It's a clean solution to the problem, you can continue monkey patching all you want and not have to worry about breaking anything.

So what will the syntax of this look like? Well, it's just an idea right now, but the proposed syntax goes something like this.

module TimeRefinements
 refine Fixnum do
   def seconds; self; end
   def minutes; self * 60; end
   def hours; minutes * 60; end

# Later on
def some_method
 using TimeRefinements
 puts 60.minutes

# But this would cause a NoMethodError
puts 60.minutes

So when can you look forward to this feature? Well, Ruby 2.0 is some time off, and you probably won't see it until then. But it's on the horizon, and it's such a natural fit, it's hard to imagine this won't be in Ruby 2.0.

  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Refinements: The End of Monkey Patching

©2014 About.com. All rights reserved.