The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Monkey Patching Core Functionality == BAD, BAD, BAD

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Kurt Schrader

Posts: 80
Nickname: kschrader
Registered: Feb, 2008

Kurt Schrader is an entrepreneur and a ruby programmer.
Monkey Patching Core Functionality == BAD, BAD, BAD Posted: Apr 24, 2008 7:18 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Kurt Schrader.
Original Post: Monkey Patching Core Functionality == BAD, BAD, BAD
Feed Title: Schrade.Blog
Feed URL: http://kurt.karmalab.org/atom.xml
Feed Description: Tech and Business Ramblings by Kurt Schrader
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Kurt Schrader
Latest Posts From Schrade.Blog

Advertisement

Yesterday, I finally got around to upgrading HAML in our Rails app to the newest stable version and the first thing that happened was that 20 completely unrelated specs broke.

Why, you may ask?

A monkey got into our code, that's why.

You see, Ruby allows you to redefine any method of any class on the fly (monkey patching) and it turns out that the old version of HAML had the following code in it:

  unless String.methods.include? 'old_comp'
  class String # :nodoc
    alias_method :old_comp, :<=>

    def <=>(other)
      if other.is_a? NilClass
        -1
      else
        old_comp(other)
      end
    end
  end

  class NilClass # :nodoc:
    include Comparable

    def <=>(other)
      other.nil? ? 0 : 1
    end
  end
end

This, in turn, snuck into our codebase in all sorts of little unexpected places. In one instance a test was comparing sorted Arrays of nils and returning true. Not good.

Luckily, in all of our cases this ended up being more of an irritant than anything else, but I can easily imagine any number of ways in which relying on the assumed behavior of these methods could have broken our app in any number of subtle and terrible ways.

So I'm only going to say this once:

Don't modify core Ruby functionality in your plugins or Rubygems.

You will break your users' codebase.

If you do modify core functionality you deserve to be slapped around by those around you.

Read: Monkey Patching Core Functionality == BAD, BAD, BAD

Topic: Small Code Commits Previous Topic   Next Topic Topic: Looking for 1001 Ways to Promote my Ruby eBook

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use