54 lines
1.5 KiB
Markdown
54 lines
1.5 KiB
Markdown
---
|
|
title: "Rake with namespaces and default tasks"
|
|
kind: article
|
|
slug: rake-with-namespaces-and-default-tasks
|
|
created_at: 2011-04-04
|
|
tags:
|
|
- Ruby
|
|
- rake
|
|
---
|
|
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`:
|
|
|
|
:::ruby
|
|
namespace :cleanup do
|
|
desc "Aggregate click stats"
|
|
task :clicks => :environment do
|
|
Click.cleanup!
|
|
end
|
|
|
|
desc "Clean old logs"
|
|
task :logs => :environment do
|
|
Log.cleanup!
|
|
end
|
|
|
|
task :all => [:clicks, :logs]
|
|
end
|
|
|
|
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.
|