A Brief Introduction to Rake
August 16, 2021
Rake is a task runner written in Ruby. It performs repetitive tasks, such as
- Making database backup
- Running tests
- Watch for file changes and compile the changed files
In the words of late Jim Weirich, the creator of rake,
The essence of rake is to take a task and break it down into its component pieces to specify what needs to be done to do the bigger task you are trying to do.
Usage
Put the following code in a Rakefile.
desc "Compile Code"
task :compile do
puts "Compiling the code."
endRun the task by running the following command
> rake compileThe description is listed when you run rake --task to see all available tasks.
> rake --task
rake compile # Compile codeDependent Tasks
task :interpret do
puts "Interpreting the code"
end
task compile: "interpret" do
puts "Compiling the code"
end> rake compile
Interpreting the code
Compiling the codeTo run multiple dependent tasks, provide their names as an array of symbols.
task compile: %i(clean sanitize interpret) do
puts "Compiling the code"
endProviding Defaults
Use the default task to specify all tasks to run when you run the rake command, without any arguments.
task default: %i[clean sanitize]
desc "Cleaning the code"
task :clean do
puts "Cleaning the code"
end
desc "Sanitizing the code"
task :sanitize do
puts "Sanitizing the code"
end > rake
Cleaning the code
Sanitizing the codeScope
You can scope tasks with similar names under different namespaces.
task :backup do
puts "Database backup"
end
namespace :file do
task :backup do
puts "File backup"
end
endrake backup
> Database backup
rake file:backup
> File backupAccess Environment Variables
task :show_state do
puts "State = #{ENV["STATE"]}"
end> export STATE=paused
> rake show_state
State = pausedRake also allows you to pass the environment variable for the particular command. It’s only valid for that specific command, though.
> rake show_state STATE=running
State = running
> rake show_state
State = pausedWhat’s Possible?
First, it’s all Ruby code. You can do anything in rake that you can do in Ruby. There’s no limit.
task :sum do
result = 0
(1..10).each do |n|
result += n
end
puts result
endHowever, rake is perfect for file manipulation. It includes the FileUtils standard library. So you can use all standard file manipulation commands.
desc "Taking a backup of the Rakefile"
task :backup do
mkdir_p "data/backup"
cp "Rakefile", "data/backup/Rakefile"
endYou can also run shell commands. This is especially handy when you want to run git add, git commit, and git push commands.
desc "git add, commit, and push"
task :track do
sh "git add ."
sh "git commit -m '#{ENV['m']}'"
sh "git push origin main"
endRun the command as follows:
> rake track m="initialize project"Finally, rake can run Ruby scripts, too.
task :run do
ruby "greet.rb"
end