Timewarping in Ruby

By Deane Barker on March 23, 2006

Time warp for functional and unit testing: Here’s a code snippet that shows just how fantastic a language Ruby truly is. In this snippet, you can extend a core class of Ruby (“Time”) so that you can override what the “Now” function returns.

This lets you “time warp” when you’re doing testing, and essentially change the time for your entire app to whatever you need it to be to test something out.

In other languages that I’ve programmed with, if you ever thought you would need to do something like this, you had to be sure to wrap calls to “Now” (or its equivalent) in a user-defined function so that you could alter the return value if you wanted.

Ruby is very much like what’s demonstrated here, all over the place. With a few lines of code, you can change the way the core of Ruby works for your app.

Do you want everything coming back from “to_s” (“ToString()”) to be prepended with, “I got ya friggin’ string right ‘ere…”? You can do this. (And yes, there are other languages that do this, but this is first one I’ve programmed with.)

I remember thinking this was insane when a bit of code showed me how I could extend the core “Object” class — from which every object inherits — to write a record to a database whenever a class — any class, anywhere, from any existing code, written at any time in the past — was instantiated.

The corollary to this, of course, is that you could bone your system something fierce if you’re not careful.