skip to content

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