Skip to Main Content
Professional Ruby on Rails™
book

Professional Ruby on Rails™

by Noel Rappin
February 2008
Intermediate to advanced content levelIntermediate to advanced
479 pages
14h
English
Wrox
Content preview from Professional Ruby on Rails™

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher
Rails 4 in Action

Rails 4 in Action

Yehuda Katz, Rebecca Skinner, Stephen Klabnik, Ryan Bigg

Publisher Resources

ISBN: 9780470223888Purchase book