O'Reilly logo

Professional Ruby on Rails™ by Noel Rappin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.2. What You Can Do for Rake

No matter how complete the predefined Rake tasks are, there are always going to be tasks specific to your project that you are going to want to automate. Because Rake is just Ruby, it's not hard to write new tasks. And as you might expect, Rails provides a couple of features to make it easy to integrate your custom Rake tasks with your entire Rails project.

The first is autoloading. Any file placed in the /lib/tasks directory and ending with the extension .rake will automatically be loaded when Rake is invoked. This means that you will be able to access your tasks from the same command line invocation of rake as the preexisting tasks, and also that your tasks will be included in the common listing for rake -T. Not only does this allow you to integrate your custom tasks, but it also facilitates keeping the rakefiles under control, because you can group related tasks into their own files.

The second feature is complete access to the Rails environment, including being able to use your ActiveRecord models in your Rake tasks and getting all the nice database connections for free.

4.2.1. A Simple Rake Task

To show you what a typical Rake task looks like, I chose a pretty basic one from the Rails distribution — the log:clear task, which resets all the log files. You can look at the source for all the Rails tasks in vendor/rails/railties/lib/tasks. Here's what log:clear looks like -- the task is named :clear inside a namepsace called :log:

namespace :log ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required