Rake

A task runner for Ruby, similar to make, for defining and running automated tasks.

Overview

Rake is a task runner for Ruby — think of it as Ruby’s answer to make. It lets you define tasks with dependencies and run them from the command line. Rake is the standard way to automate repetitive jobs in Ruby projects, from running tests to generating documentation.

Setup

To install run gem install rake.

Most Ruby projects include Rake by default via the Gemfile:

# Gemfile
gem 'rake'

Defining Tasks

Create a file named Rakefile in your project root:

# Rakefile

desc "Say hello"
task :hello do
  puts "Hello, Rake!"
end

desc "Run tests"
task :test do
  sh "rspec spec/"
end

desc "Build the project"
task :build => [:test] do
  sh "gem build mygem.gemspec"
end

List available tasks:

rake -T
# rake hello  # Say hello
# rake test   # Run tests
# rake build  # Build the project

Run a task:

rake hello
# Hello, Rake!

File Tasks

File tasks create files only when their sources are newer, which avoids unnecessary rework:

file "output.txt" => ["input1.txt", "input2.txt"] do
  sh "cat input1.txt input2.txt > output.txt"
end

Namespaces

Group related tasks under a namespace:

namespace :db do
  desc "Create the database"
  task :create do
    sh "createdb myapp_development"
  end

  desc "Drop the database"
  task :drop do
    sh "dropdb myapp_development"
  end
end
rake db:create
rake db:drop

Passing Arguments

Tasks can accept parameters:

desc "Greet someone by name"
task :greet, [:name] do |t, args|
  args.with_defaults(name: "World")
  puts "Hello, #{args.name}!"
end
rake "greet[Alice]"
# Hello, Alice!

Source

Source is found at github.com/ruby/rake.