Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 134 ยท Metaprogramming

Monkey Patching and Safe Alternatives

Learn what monkey patching is in Ruby, why open classes are risky, and how prepend wrappers, refinements, subclasses and delegation keep code safe.

In Ruby, no class is closed. You can reopen String, Integer, Array or any class from a gem and add or replace methods. Changing an existing class this way is called monkey patching. It is why Rails can offer 3.days.ago and why a small script can teach Integer to answer 5.factorial. It is also a leading cause of mysterious bugs, because a patch is global: every piece of code in the process sees it, including libraries that never expected it.

This lesson shows how reopening works, what can go wrong (with real failing examples), and a ladder of safer alternatives: adding new methods carefully, wrapping with prepend, refinements, subclassing and delegation. By the end you will know when a patch is acceptable and what to reach for instead.

Reopening a class: the basic move

Ruby Adding a method to a core class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class Integer ... end form does not create a new class; because Integer already exists, Ruby reopens it and adds factorial. From then on every integer in the program has the method. Adding a new, uniquely named method like this is the mildest form of monkey patching. The risk is small, but it is not zero: if a library later defines its own factorial with different behavior, whichever file loads last silently wins.

Replacing a method: where the danger starts

Overriding an existing method changes behavior for everybody, including Ruby's own library code that calls it.

Ruby A patch that breaks unrelated code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After the patch, scores.sum returns the string "patched!" for every caller in the process, even inside gems that compute totals. The remove_method :sum at the end deletes the replacement defined directly in Array, and the original from Enumerable shows through again, returning 60. In real programs you rarely get that chance to undo a patch, which is the whole problem.

Patching core classes is global state. A change made in one file silently changes behavior in every other file, test and gem, and the bug shows up far from the patch. Two libraries that patch the same method can break each other depending on load order.

The classic failure: two patches, one method

Here two "libraries" both patch String#to_s-style behavior in incompatible ways. Whichever loads second wins, and the first one's tests quietly break.

Ruby Last patch wins (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Library A expected hyphens, library B returns underscores, and neither knew about the other. The program ends with main.rb:21:in '<main>': slugify no longer matches library A: ruby_fast_fun (RuntimeError). Ruby warns about redefined methods only in verbose mode (ruby -w), and the runner does not show it. The lesson is that you cannot rely on Ruby to alert you.

Safer alternative 1: prepend a module (wrap, don't replace)

When you must change the behavior of an existing method (for example to log, cache or tweak the result), put your code in a module and prepend it. The module sits in front of the class in the ancestors, and super reaches the original.

Ruby A prepend wrapper with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The original class stays untouched. The wrapper is a named module you can find in the ancestors, test on its own, and remove from your code in one place. This is the technique of choice for changing existing methods of your own classes or of a gem. Compare it with the older alias_method chain (alias_method :old_total, :total followed by a new total that calls old_total), which breaks easily if two files do it with the same alias name and cannot be undone cleanly. If you only want to add behavior to your own classes, a plain include of a module is enough.

Safer alternative 2: refinements

A refinement is a patch that is active only where you ask for it. Other files, libraries and tests still see the original class.

Ruby A refinement scoped to one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After using Shouting, code later in this file sees shout: the second and third lines print RUBY!, and even respond_to? agrees from there. Code written before the using line (the Before class) does not see it, so its check prints false. Refinements are lexical: what matters is where the calling code is written, not which object receives the call. A library in another file never sees your refinement. That narrow scope is the feature. The costs are a little extra thinking and some surprises with dynamic code that is evaluated elsewhere, so refinements suit library authors and careful application code more than quick scripts.

Safer alternative 3: subclass, wrapper, delegation

Often you don't need to change String at all.

Ruby A subclass and a delegating wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A subclass such as Slug is a new type: it can have extra methods without touching String. Be aware that many core methods return plain String/Array objects, not your subclass (the upcase.class line prints String), which is why subclassing core classes is usually less pleasant than wrapping. A wrapper object exposes exactly the interface you want, and Forwardable lets you delegate selected methods (more in Forwardable and Delegation). A plain helper method or module function (Slugs.from(text)) is often the simplest answer of all.

Safer alternative 4: extend one object

If you need extra behavior on one object only, use extend or a singleton method. No other object is affected.

Ruby Changing one object, not the class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Making a patch less dangerous when you must

Sometimes patching is the right call: backporting a method to an older Ruby, fixing a bug in a gem you cannot upgrade, or adding a helper in a test suite. Follow the monkey patching code of conduct:

  1. Add, don't replace. New, clearly named methods are safe; changing existing ones is not.
  2. Isolate in one file (for example lib/core_ext/string.rb), named after the class, loaded in one place.
  3. Check before you define. Guard with unless method_defined?(:name) so a future Ruby or gem that provides the method wins.
  4. Use prepend + super to change existing behavior, never copy the original body.
  5. Document the patch, and add a test that fails if the gem or Ruby changes the patched method.
  6. Leave a removal note: write the Ruby or gem version that makes the patch unnecessary.
  7. Prefer refinements where using fits your code structure.
Ruby A defensive core extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The patch lives in a named module (visible in ancestors, easy to test), and the guard means a later definition of blank? from elsewhere is not overwritten. Because the method comes from an included module rather than from String itself, it can also be overridden normally.

Detecting patches and debugging

When a core method behaves strangely, ask Ruby where it comes from:

Ruby
"x".method(:strip).owner             # => String
"x".method(:strip).source_location   # => nil for built-in C methods, a file and line for patches

A non-nil source_location on a core method is a strong sign of a monkey patch, and the file and line tell you who made it (see Reflection and Introspection). Running Ruby with -w also warns about redefined methods.

Summary of the ladder

Need Prefer
A brand-new helper for a core type A module function or helper method; or a guarded core extension
Change an existing method prepend a module and call super
A patch visible only to some code Refinements with using
A new kind of string/array/hash Subclass or wrapper with delegation
Behavior for one object extend or define_singleton_method
A hard bug in a gem Prepend patch in one file, with a test and a removal note

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes monkey patching risky?

    A patch changes a class for the whole process, so unrelated code can break and two patches can conflict depending on load order.
  2. 2. What is the main advantage of prepend with super over replacing a method?

    A prepended module is found first in the ancestors, and super reaches the original method. The original class stays untouched.
  3. 3. Where does a refinement take effect?

    Refinements are lexically scoped: they apply after using in that file, so other code still sees the original class.
  4. 4. You must patch a gem method. Which guideline fits best?

    A single, documented prepend with a test keeps the change visible, reversible and verifiable.
  5. 5. A core method Array#sum returns surprising results. How can you check whether it was monkey patched?

    Built-in C methods report nil for source_location. A path and line number reveals Ruby code that replaced or wrapped the method.

Summary

  • Ruby classes are open, so you can reopen core and library classes; changing them in place is called monkey patching.
  • Patches are global: they can break unrelated code, and conflicting patches silently depend on load order.
  • Adding a new, uniquely named method is mild; replacing an existing one is dangerous.
  • Prefer prepend plus super to change behavior, refinements for file-scoped additions, and subclasses, wrappers, Forwardable or extend on one object when you can.
  • If you must patch, isolate it in one file, guard it, document it, test it, and note when it can go.
  • Use method(:x).owner and source_location to discover who changed a method.

Next: eval and Binding