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, ...
Get Professional Ruby on Rails™ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.