Last updated

Rake with namespaces and default tasks

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:

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

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

 1namespace :cleanup do
 2  desc "Aggregate click stats"
 3  task :clicks => :environment do
 4    Click.cleanup!
 5  end
 6
 7  desc "Clean old logs"
 8  task :logs => :environment do
 9    Log.cleanup!
10  end
11
12  task :all => [:clicks, :logs]
13end
14
15desc "Cleanup everything"
16task :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.

Tags: Ruby rake