# euccas.github.io

## why a developer writes

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.

# Rakefile

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 Rakefile or rakefile.

Example:

# Namespaces

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.

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 :default keyword.

# Multiple Tasks Running in Parallel

Rake’s 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:

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.

# View all the Rake tasks

To get an overview of all the defined Rake tasks, use rake -T

# 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 .rake files.

Include one rakefile:

Include multiple rakefiles in nested directories:

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

next will discard the following codes in the current rake task, and process the following part of the other tasks if there are any.

• fail/raise
• exit

• abort

When abort is used in a rescue block, it terminates the task as well as prints the whole error (even without using –trace).