Automating Tasks with Rake

Rake is available as the rake gem; if you've installed Rails, you already have it. Unlike most gems, it doesn't just install libraries: it installs a command-line program called rake, which contains the logic for actually performing Rake tasks.

A Rakefile is just a Ruby source file that has access to some special methods: task, file, directory, and a few others. Calling one of these methods defines a task, which can be run by the command-line rake  program, or called as a dependency by other tasks.

The most commonly used method is the generic one: task. This method takes the name of the task to define, and a code block that implements the task. Here's a simple Rakefile that defines two tasks, cross_bridge  and build_bridge, one of which depends on the other. It designates cross_bridge as the default task by defining a third task called default which does nothing except depend on cross_bridge.

# Rakefile

 desc "Cross the bridge."
 task :cross_bridge => [:build_bridge] do
   puts "I'm crossing the bridge."
 end

 desc "Build the bridge"
 task :build_bridge do
   puts 'Bridge construction is complete.'
 end

 task :default => [:cross_bridge]

Call this file Rakefile, and it'll be automatically picked up by the rake command when you run the command in its directory. Here are some sample runs:/

 $ rake
 Bridge construction is complete.
 I'm crossing the bridge.

 $ rake build_bridge
 Bridge construction is complete.

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Remove duplicates from a JavaScript Array

Sending Binary Data over the Network with Json