Organizing Rake Using Namespaces

I use Rake to automate a lot of tasks, in my plugins and on my development systems. A good technique to learn is to organize and group your tasks using Rake namespaces.

Example:

desc "Download missing plugins from Github"
task :plugins do
  # ..
end
 
namespace :plugins do
  desc "Fetch latest revisions"
  task :fetch do
    # ..
  end
 
  desc "Push latest revisions"
  task :push do
    # ..
  end
 
  desc "Cleanup repos"
  task :gc do
    # ..
  end
end

In this example I use Rake’s namespaces to organize and group similar tasks. This shows up when I run rake on the command line like:

rake plugins        # Download missing plugins from Github
rake plugins:fetch  # Fetch latest revisions
rake plugins:gc     # Cleanup repos
rake plugins:push   # Push latest revisions

By organizing rake into namespaces I don’t have to come up with a_unique_and_really_long_task_name for every task.

Another nice feature of Rake namespaces is that you can reopen them and add to them, either in the same file or a different file. The following example is the same as the first.

desc "Download missing plugins from Github"
task :plugins do
  # ..
end
 
namespace :plugins do
  desc "Fetch latest revisions"
  task :fetch do
    # ..
  end
end
 
namespace :plugins do
  desc "Push latest revisions"
  task :push do
    # ..
  end
end
 
namespace :plugins do
  desc "Cleanup repos"
  task :gc do
    # ..
  end
end

While I recommend the first example instead of the second one when your tasks are all in a single file, reopening becomes useful when you are trying to use a common namespace that was defined somewhere else (e.g. inside Rails).

With plugins it is also good to prefix your plugin’s tasks in a namespace so they don’t conflict with other tasks.

If you need more rake namespace examples, post a comment below. I have a bunch of them I’ve written and I’d be happy to share.