Rake
Rake is Rubys make. Tasks live in a Rakefile (or under lib/tasks/*.rake in Rails), grouped into namespaces, and form a dependency graph — running a task runs its prerequisites first. It is the right place for cron-style chores: data backfills, report generation, cache warm-ups, deployment helpers.
A Rakefile with namespaces, deps, and arguments
EXAMPLE
# Rakefile
require "fileutils"
require "json"
# Default task runs when you type just `rake`
task default: %i[test lint]
desc "Run the test suite"
task :test do
sh "bundle exec rspec --fail-fast"
end
desc "Run RuboCop"
task :lint do
sh "bundle exec rubocop --parallel"
end
namespace :db do
desc "Apply pending migrations"
task :migrate do
sh "bundle exec rails db:migrate"
end
desc "Reset and reseed the dev database"
task reset: %i[migrate] do
sh "bundle exec rails db:reset db:seed"
end
# Task with arguments and a prerequisite
desc "Backfill nullable column for a date range — rake db:backfill[2026-01-01,2026-06-01]"
task :backfill, [:from, :to] => :migrate do |_t, args|
args.with_defaults(from: "2026-01-01", to: Date.today.to_s)
sh %{bundle exec rails runner "Order.where(paid_at: \#{args.from}..\#{args.to}).find_each(&:backfill!)"}
end
end
namespace :report do
desc "Write a daily revenue JSON to tmp/"
file "tmp/revenue.json" do |t|
FileUtils.mkdir_p("tmp")
data = { generated_at: Time.now, rows: [] }
File.write(t.name, JSON.pretty_generate(data))
end
task :daily => "tmp/revenue.json"
end
# Discoverability: `rake -T` prints every task with its desc.
# Force a re-run even if `file` task says it is up to date: `rake -f`.
# Invoke programmatically:
# Rake::Task["db:reset"].invoke
# Rake::Task["db:backfill"].invoke("2026-05-01", "2026-05-31")
Why it matters
Always give tasks a `desc` — without one, the task is invisible to `rake -T`, which is how teammates discover what you have built. Reach for `file` tasks when output is genuinely a file: Rake compares mtimes and skips work that is already up to date.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
# Rakefile
task :hello do
puts 'hi from rake'
end
# Run: bundle exec rake hello
Try it Yourself »
Discussion
Loading…