Rails Console Secrets

Jeffrey Hardy,
Sep 19, 2007

This is an oldish link, but it’s a good one, especially for those folks who aren’t yet Rails console ninjas.

Secrets of the Rails Console Ninjas by Amy Hoy.

For the unenlightened, Ruby comes with a an interactive interpreter called irb (for Interactive Ruby). Rails harnesses the power of irb to give you an interactive console for your application (hereafter referred to as simply “the console”). The advantage of the console is that it enjoys the special privilege of being fully integrated with your project’s environment. This means it has access and knowledge of your models (and subsequently, your database). You can execute any arbitrary Ruby code inside the console and do anything you might otherwise do inside your Ruby programs: set variables, evaluate conditions, and inspect objects. The only essential difference between an interactive session and a regular old Ruby program is that console will echo the return value of everything it executes. This saves you from having to explicitly print the results of an evaluation. Just run the code, and you’ll see the results.

We use the console pretty heavily in the book, so for the most part, you learn by doing. But there are definitely some tricks here that we didn’t mention. So, if you’re wondering about things like:

  • Specifying console environment (./script/console production)
  • Getting out of a block of code (ctrl + c)
  • Accessing the last return value (_)
  • Reloading the console (reload!)

Then you should check out Amy’s article. There’s also a collection on Stupid console tricks!

For further reading, check out Chris Wanstrath’s classic article irb Mix Tape, which is full of other amazing goodies that will make your day.

Comments

Leave a response