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
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.
cleanup has the same name as the namespace and calls the
cleanup:all task, kicking off the entire cleanup
If you're seeing this message you've probably enabled some form of adblocker. I respect that.
I use this space to show recommended books on Amazon.com in relation to the post you just read. This generates a small income that allows me to buy a book every now and then.