2017-03-20 15:35:19 +00:00
|
|
|
+++
|
|
|
|
date = "2011-04-04"
|
|
|
|
title = "Rake with namespaces and default tasks"
|
|
|
|
tags = ["Ruby", "rake"]
|
|
|
|
slug = "rake-with-namespaces-and-default-tasks"
|
|
|
|
+++
|
2015-03-26 11:28:08 +00:00
|
|
|
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:
|
|
|
|
|
2017-03-20 15:35:19 +00:00
|
|
|
``` shell
|
|
|
|
rake cleanup # Cleanup everything
|
|
|
|
rake cleanup:clicks # Aggregate click stats
|
|
|
|
rake cleanup:logs # Clean old logs
|
|
|
|
```
|
2015-03-26 11:28:08 +00:00
|
|
|
|
|
|
|
Here's what I put in `lib/tasks/cleanup.rake`:
|
|
|
|
|
2017-03-20 15:35:19 +00:00
|
|
|
``` ruby
|
|
|
|
namespace :cleanup do
|
|
|
|
desc "Aggregate click stats"
|
|
|
|
task :clicks => :environment do
|
|
|
|
Click.cleanup!
|
|
|
|
end
|
2015-03-26 11:28:08 +00:00
|
|
|
|
2017-03-20 15:35:19 +00:00
|
|
|
desc "Clean old logs"
|
|
|
|
task :logs => :environment do
|
|
|
|
Log.cleanup!
|
|
|
|
end
|
2015-03-26 11:28:08 +00:00
|
|
|
|
2017-03-20 15:35:19 +00:00
|
|
|
task :all => [:clicks, :logs]
|
|
|
|
end
|
2015-03-26 11:28:08 +00:00
|
|
|
|
2017-03-20 15:35:19 +00:00
|
|
|
desc "Cleanup everything"
|
|
|
|
task :cleanup => 'cleanup:all'
|
|
|
|
```
|
2015-03-26 11:28:08 +00:00
|
|
|
|
|
|
|
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.
|
2017-03-20 15:35:19 +00:00
|
|
|
|
|
|
|
|