Rake with namespaces and default tasks

4 April 2011

Rake is an awesome tool to automate tasks for your Ruby (or Rails) application. In this short article I’ll show you how to use namespaces and set default tasks for them. ~ Let me first tell you what I want to accomplish. I have a Rails application that needs to be cleaned up occasionally. Essetially we delete old data from the database.

There are several models that each implement a cleanup! method which takes care of cleaning up data. Now all I need is a few rake tasks to kick off the clean up process.

This is what I’d like:

rake cleanup         # Cleanup everything
rake cleanup:clicks  # Aggregate click stats
rake cleanup:logs    # Clean old logs

Here’s what I put in lib/tasks/cleanup.rake:

namespace :cleanup do
  desc "Aggregate click stats"
  task :clicks => :environment do

  desc "Clean old logs"
  task :logs => :environment do

  task :all => [:clicks, :logs]

desc "Cleanup everything"
task :cleanup => 'cleanup:all'

Notice that the cleanup:all task does not have a description. Without it, it won’t show up when you do a rake -T to view available tasks.

The task cleanup has the same name as the namespace and calls the (undocumentend) cleanup:all task, kicking off the entire cleanup process.