Refinements – Ruby Monkey-Patching Redifined

Bookmark and Share

Ruby classes are special in many ways. One of the most useful among these specialities is that, in Ruby, all classes are mutable. The ability to change the way classes behave at runtime(aka monkey-patching) has been used by many libraries and frameworks to decorate Ruby’s core classes with additions and/or replacements. But good and evil are two sides of a coin. Anything that helps you a lot can also get you into problems.

Many patterns in Ruby are built around the ability to modify classes. But, the problem rises if a library patches code in a way the user does not expect (or want), or if two libraries try to apply conflicting patches. Sometimes, you simply don’t want patches to be applied globally, and this is where refinements come in. Refinements are intended to allow monkey-patching only within certain limited scopes, like within a library that wants to use altered or enhanced versions of core Ruby types without affecting code outside the library. Refinements are defined in a module using the refine method. It takes a single argument, the class you want to change the behavior of, as well as a block. Inside this …

Read More