Rake is the build language for Ruby programs, originally developed by Jim Weirich. It’s a standard library in Ruby 2.1. You can define tasks with Rake: named code blocks that carry out specific actions, such as running unit tests, deploy your code to github, etc. In this post, I’ll write about the basics of Rake and how to use it to automate the tasks of your Ruby projects.
In order to use Rake to define tasks, first you need a Rakefile. A Rakefile is a Ruby source file that has access to some special methods: task, file, directory, and a few others. A task defined in the Rakefile can be run by the command-line
rake program, or be called as a dependency by other tasks. The name of Rakefile can be
Write Descriptions for Rake Tasks
Writing a description to the defined tasks in Rakefile help you get more details about the task and know better what it does.
1 2 3 4
Using namespaces is a good way to group similar tasks in Rakefile. You’ll need specify the namespace when calling a task inside it. One example as you can see from Rails is this command
In this command, the db is the namespace, and the migrate is the task inside the namespace.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The default task is the one gets executed when you run rake without any arguments. You can set the default task in Rakefile by using the
Multiple Tasks Running in Parallel
multitask function supports running multiple tasks in parallel. The method is defining a task using the
multitask function, and each of this task’s prerequisites will be run in a separate thread.
An example of multiple parallel tasks:
1 2 3 4 5 6 7 8 9 10 11 12
In this example, the
build_serial task runs in about 15 seconds, but the
build_parallel task runs in about 10 seconds.
Rake tasks can be invoked from other tasks using the
Rake::Task['<your take>'].invoke method.
1 2 3 4 5 6
View all the Rake tasks
To get an overview of all the defined Rake tasks, use
Include external rakefiles
When your project need include the Rake tasks defined in external directories, you’ll need include the external rakefiles into your project. The way to do it is using the
import. Note the
require won’t work here, as it looks for the
.rb files instead of the
Include one rakefile:
Include multiple rakefiles in nested directories:
1 2 3 4
Exit from Rake tasks
In a Ruby function, you can use
return in the function when you want to exit (early). But in Rake tasks, the
return is an invalid method to use, because each Rake task is actually a
Proc. To exit early from a Rake task, you can use one of the following methods:
next will discard the following codes in the current rake task, and process the following part of the other tasks if there are any.
1 2 3 4 5 6
When abort is used in a rescue block, it terminates the task as well as prints the whole error (even without using –trace).