Ripped from Rails core extensions. There's a note in my comment in #1095 :)