Posted on: Written by: K-Sato
⚠️ This article was posted over 2 years ago. The information might be outdated. ⚠️

Table of Contents

What is rake

Rake is a task runner.

How to Write a Rake Task

Here’s a simple Rake task:

namespace :greet do
  desc "Say Hello"
  task hello: :environment do
    puts "Hello"
  end
end

You can put this code inside a file named Rakefile, or if you’re using Rails, you can save this under lib/tasks/apple.rake.

To run this task:

$ rake greet:hello

Dependent Tasks

Rake allows you to define a list of other tasks that must run before the current task.

Example:

task :first do
  puts "Run this task first"
end

task :second => [:first] do
  puts "Should put this after :first"
end

This would return:

Run this task first
Should put this after :first

Execute something after migration

namespace :db do
  def my_appended_code
    puts 'this code gets run after the original rails db:migrate task'
    puts 'it only runs if the migration did not throw any exceptions'
  end

  task :migrate do
    my_appended_code
  end
end

References

About the author

I am a web-developer based somewhere on earth. I primarily code in TypeScript, Go and Ruby at work. React, RoR and Gin are my go-to Frameworks.