skip to content

Custom Rake & Thor Tasks

Apps extend bin/rails with lib/tasks/*.rake files that load the app through the :environment prerequisite, and with Thor generators built on NamedBase. Interviewers ask when a task beats a migration.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails 8.1 app, where do custom Rake tasks live, and what does bin/rails generate task loyalty recompute write?

level: juniorimportance: must knowfreq 58%

answer

  1. lib/tasks, any .rake file below it
  2. Rakefile calls Rails.application.load_tasks
  3. namespace block per file
  4. desc "TODO" and :environment in the stub
  5. run as bin/rails loyalty:recompute

basics

~20 s

Custom tasks live in .rake files under lib/tasks, which the app's Rakefile loads through Rails.application.load_tasks. bin/rails generate task loyalty recompute writes lib/tasks/loyalty.rake with a loyalty namespace and a recompute task stub that has desc "TODO" and the :environment prerequisite.

solid answer

~40 s

A new app's `Rakefile` requires `config/application` and calls `Rails.application.load_tasks`, which loads every `lib/tasks/**/*.rake` file, alongside the tasks Rails and your gems define. So a custom task is just a `.rake` file there; no registration is needed. `bin/rails generate task loyalty recompute` writes `lib/tasks/loyalty.rake` containing `namespace :loyalty do`, a `desc "TODO"` line and `task recompute: :environment do ... end`; pass several action names to get several stubs in one namespace. You run it as `bin/rails loyalty:recompute`. Replace the `TODO` with a real description, since `desc` is what makes the task show in `bin/rails -T`, and keep the task body thin: call a model or plain Ruby object that holds the logic, so it can be tested without Rake.

code

bash · 4 lines
bash
bin/rails generate task loyalty recompute
#   create  lib/tasks/loyalty.rake
bin/rails loyalty:recompute
RAILS_ENV=production bin/rails loyalty:recompute

go deeper

for a junior

Know that tasks live in lib/tasks/*.rake, that bin/rails generate task writes a namespaced stub, and that you run it as bin/rails namespace:task.

for a middle

Explain how the Rakefile's load_tasks picks the files up, why desc matters for -T, and why the stub includes :environment.

for a senior

Keep tasks thin and tested by delegating to app code, name them by domain, and remove one-off tasks once they have run in every environment.

for a principal

Decide which operational work belongs in tasks versus jobs or admin screens, and how tasks are reviewed, documented and retired across the codebase.

## Where Rails looks for tasks Every generated Rails app has a `Rakefile` at its root: ```ruby require_relative "config/application" Rails.application.load_tasks ``` `load_tasks` collects tasks from three places: - **Rails itself**: `db:*`, `tmp:*`, `log:*`, `time:zones` and the rest of the framework tasks; - **gems and engines** whose railties register tasks; - **your application**: every file matching `lib/tasks/**/*.rake`, loaded in sorted order. The comment Rails writes into the `Rakefile` says the same: add your own tasks in files under `lib/tasks` ending in `.rake`, and they become available automatically. Subdirectories work too, which helps once an app has dozens of tasks. ## What generate task writes `bin/rails generate task loyalty recompute expire` writes one file, `lib/tasks/loyalty.rake`: ```ruby namespace :loyalty do desc "TODO" task recompute: :environment do end desc "TODO" task expire: :environment do end end ``` Three conventions are baked in: 1. **One namespace per file**, named after the first argument, so tasks are called `loyalty:recompute` and `loyalty:expire`. 2. **A `desc` line on every task.** Rake lists only described tasks in `bin/rails -T`, so a task with no `desc` works but is invisible to anyone browsing the list. The generator writes `"TODO"` to remind you to fill it in. 3. **The `:environment` prerequisite**, which boots the application before the task body runs, so models such as `Customer` and `Purchase` are available. ## Running the task | Command | What happens | |---|---| | `bin/rails loyalty:recompute` | runs the task in development | | `RAILS_ENV=production bin/rails loyalty:recompute` | runs it against production | | `bin/rails -T loyalty` | lists the described tasks matching `loyalty` | `bin/rails` finds no Rails command named `loyalty:recompute` and hands it to Rake, so it runs exactly as `bin/rake loyalty:recompute` would. ## Keeping tasks maintainable A Rake task is an **entry point**, not a place for business logic: - Put the work in a model method or a plain Ruby class under `app/` (for example `Loyalty::Recalculator`), and have the task call it. The class can then be unit-tested, reused from a job, and called from the console. - Write a real `desc` that says what the task changes and how to call it. - Namespace by domain (`loyalty:`, `billing:`), not by author or date. - Delete one-off tasks after they have run everywhere; a `lib/tasks` folder full of stale backfills misleads the next reader. - Log what the task did (counts, ids processed) through `Rails.logger` or `puts`, so the person running it can see progress. ## Common mistakes - Putting the file in `app/tasks` or `config/` and wondering why `bin/rails -T` does not list it; only `lib/tasks` is loaded. - Using a `.rb` extension; the loader only picks up `.rake` files. - Leaving `desc "TODO"` in place, which ships a useless description. - Dropping `:environment` and then getting `NameError` for the first model the task touches. ## Testing a task Because the task body only delegates, most testing happens on the class it calls. When the task's own wiring matters (argument parsing, the namespace name), a test can load and invoke it: 1. `Rails.application.load_tasks` once in the test, so every `.rake` file is read. 2. `Rake::Task["loyalty:recompute"].invoke` to run it. 3. `Rake::Task["loyalty:recompute"].reenable` afterwards if another test invokes it again in the same process. Keeping this to one smoke test per task is usually enough; the behaviour itself is covered where the logic lives. ## Naming and discoverability - Prefer verbs for task names (`recompute`, `expire`, `export`) and nouns for namespaces (`loyalty`, `stores`). - Mention required input in the `desc` text, for example `(STORE_ID=n)`, so `bin/rails -T` doubles as documentation. - Avoid a namespace that collides with a framework one such as `db` or `assets`: tasks with the same name are merged by Rake, and an app task named `db:seed` would add its body to Rails' own.

  • Why does a task in lib/tasks/loyalty.rake without a desc line not appear in bin/rails -T?
    Rake's task listing shows only tasks that have a description, and `desc` sets it for the next task defined. The task still runs when called by name, but nobody browsing `bin/rails -T` will find it. The task generator writes `desc "TODO"` precisely so you replace it with a real description.
  • Why keep the logic of a Rake task in a class under app/ instead of the task block?
    A task block is hard to unit-test and impossible to reuse. Moving the work into a model method or a plain Ruby object, such as `Loyalty::Recalculator`, lets you test it with ordinary tests, call it from a job or the console, and keep the `.rake` file as a few lines that parse input and report results.

  • Custom tasks must be registered in config/application.rb
  • Task files belong in app/tasks so Zeitwerk autoloads them
  • A lib/tasks/loyalty.rb file is picked up like a .rake file
  • Tasks without desc cannot be run by name
  • generate task writes one file per task action
open as a page

In a Rails 8.1 Rake task, what does the :environment prerequisite actually load, and what changes when the task also takes arguments?

level: middleimportance: must knowfreq 50%

basics

~20 s

The Rakefile only loads config/application.rb; the :environment prerequisite runs Rails' environment task, which requires config/environment.rb and initializes the app, without eager loading by default. With arguments the form is task :recompute, [:store_id] => :environment, called as bin/rails "loyalty:recompute[42]".

open as a page

In a coffee-chain Rails 8.1 app, should a one-off backfill that recomputes every customer's loyalty points live in a migration or a Rake task, and why?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Put it in a Rake task. Migrations should describe schema and run at deploy time, inside a transaction on PostgreSQL, and since Rails 8.0 a fresh database loads schema.rb instead of replaying them. A task can be batched, idempotent, rerun, dry-run first and deleted once done.

open as a page

How do you build a custom Rails 8.1 generator with bin/rails generate generator, and what do NamedBase, source_root and Thor actions give you?

level: seniorimportance: should knowfreq 25%

basics

~20 s

bin/rails generate generator reward writes lib/generators/reward/ with a RewardGenerator subclass of Rails::Generators::NamedBase, a USAGE file, a templates folder and a test. NamedBase supplies the name argument and helpers such as file_name; source_root points at templates; each public method runs Thor actions in order.

open as a page

What is a Rails application template, and how does bin/rails app:template apply one to an existing Rails 8.1 app?

level: middleimportance: nice to knowfreq 16%

basics

~10 s

An application template is a Ruby script run with Rails' generator actions (gem, generate, route, initializer, rails_command). bin/rails app:template LOCATION=path-or-URL applies it to an existing app, then runs bundle install and the after_bundle blocks.

open as a page