O'Reilly logo

Professional Ruby on Rails™ by Noel Rappin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.4. Monkey Patching and Duck Punching

One of Ruby's most distinctive features is that class definitions never close — you can always add new methods to existing classes, even classes that are in the core Ruby library. I've already shown you some examples of this functionality in action, most of which have been along the lines of adding utility methods to core classes like this:

require 'rss/2.0'
class Array
  def to_rss_feed(title, link, description="")
    rss = RSS::Rss.new("2.0")
    channel = RSS::Rss::Channel.new
    rss.channel = channel
    channel.title = title
    channel.link = link
    channel.description = description
    self.each do |item|
      channel.items << item.to_rss_item
    end
    rss.to_s
  end
end

The feature is still controversial. The most commonly used term for it — monkey patching — comes out of the Python community, and was originally a derogatory way of describing the practice of changing classes at runtime (which can be done in Python, although somewhat awkwardly). Ruby programmers adopted the phrase as their own, although there has been some searching for an alternate term with a less negative connotation. However, the phrase presented as an alternative — duck punching — doesn't sound like all that much of an improvement.

Anyway, the question at hand is "Monkey Patching: Threat or Menace?" Strict software-engineering types argue that the ability to change the definition of any method in the system at whim is a recipe for chaos — "How can you verify the correctness of a program," they argue, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required