3 cool things you might not have known about Rakefiles

Author: Samuel Williams When: Thursday, 08 December 2016

Rake provide an easy to use task execution mechanism, but it also has some useful logic for extending existing tasks. Here are a few examples of the kinds of Rake tasks I've been using to make my life easier.

Chaining Tasks

It's possible for one task to call another, but it's also possible for this to go between namespaces:

namespace :db do
	task :environment => :environment do
		puts "db:environment"
	task :migrate => :environment do
		puts "db:migrate"

task :environment do
	puts "environment"

Running $ rake db:environment will invoke both the db:environment and environment tasks.

We use this to integrate with other task libraries, e.g. ActiveRecord.

Stateful Tasks

Sometimes it's useful to have stateful tasks:

LOGGER = Logger.new

task :verbose do
	LOGGER.level = Logger::DEBUG

task :deploy do
	# ...

# invoke as rake verbose deploy

Running $ rake verbose deploy will print out more detailed information.

We use this when running tasks as background jobs - verbose is not defined unless we want extra output for debugging.

Stateful Pipelines

You can use this to make flexible filters and tasks which can be configured to do different things:

namespace :dump do
	task :users do
		@records = Users.all
	task :posts do
		@records = Posts.all
	task :updated_recently do
		@records = @records.where("updated_at > ?", 6.months.ago)
	task :as_json do
	task :as_xml do

We use tasks like these to export data for customers - we almost always have some specific requirements - but we can usually chain together a set of existing tasks to get the desired output.

Multiple Tasks

It's possible to define multiple tasks with the same name. This is useful if you want to combine multiple files containing tasks

task :deploy do
	puts "Deploy 1"

task :deploy do
	puts "Deploy 2"

Running $ rake deploy will invoke both tasks.

We use this to keep our .rake files simple, focused and organised.


There are currently no comments.
[City], [Country]
Publicly displayed.
Your email won't be displayed.
The following tags are preserved: <pre>, <em> and <a>. All comments are moderated.

Please note, you can leave a comment that uses (limited) XHTML and Textile syntax.