In a Rails 8.1 Rake task, what does the :environment prerequisite actually load, and what changes when the task also takes arguments?
answer
- Rakefile loads config/application only
- environment task requires config/environment.rb
- rake_eager_load defaults to false
- [:store_id] => :environment
- quote brackets for zsh
basics
~20 sThe 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]".
solid answer
~40 s`bin/rails` loads the `Rakefile`, which requires `config/application.rb` and defines tasks but does not initialize the app. Rails defines a task named `environment` that sets `config.eager_load` to `config.rake_eager_load` (false by default) and then requires `config/environment.rb`, which runs `Rails.application.initialize!`: initializers, database configuration, autoloading. A task that lists `:environment` as a prerequisite gets all of that before its body; one that does not hits `NameError` on the first model. Because tasks do not eager load even in production, code that depends on every class being loaded (such as `ApplicationRecord.descendants`) sees only what has been autoloaded so far. With arguments, the prerequisite moves into a hash: `task :recompute, [:store_id] => :environment do |task, args|`, invoked as `bin/rails "loyalty:recompute[42]"`, quoted because zsh treats brackets as a glob.
code
ruby · 14 lines# lib/tasks/loyalty.rake
namespace :loyalty do
desc "Recompute points for one store"
task :recompute, [:store_id] => :environment do |_task, args|
store = Store.find(Integer(args.fetch(:store_id)))
Loyalty::Recalculator.new(store:).call
end
desc "List every model (forces eager loading first)"
task models: :environment do
Rails.application.eager_load!
puts ApplicationRecord.descendants.map(&:name).sort
end
endgo deeper
Remember that a task touching models needs :environment, and that tasks run with bin/rails namespace:task.
Explain the two stages, Rakefile definition then environment initialization, the rake_eager_load default, and the hash form for arguments plus prerequisites.
Anticipate the production differences: lazy loading in tasks, environment selection through RAILS_ENV only, and argument parsing that should validate and cast input.
Standardize how operational tasks take input, boot and log, so that tasks run from CI, cron or a deploy behave predictably across environments.
## Two stages of loading Running `bin/rails loyalty:recompute` goes through two distinct stages: 1. **Task definition.** Rails' command dispatcher hands the name to Rake, which loads the app's `Rakefile`. That file does `require_relative "config/application"` and `Rails.application.load_tasks`. At this point the application **class** exists and every `.rake` file has been read, but the application has **not** been initialized: no initializers have run, the autoloaders are not set up, and the database configuration is not loaded. 2. **Task execution.** Rake runs the requested task, first running its prerequisites. The gap between those stages is why `:environment` exists. ## What the environment task does Rails defines the task itself when it loads tasks: ```ruby task :environment do ActiveSupport.on_load(:before_initialize) { config.eager_load = config.rake_eager_load } require_environment! end ``` - `require_environment!` requires `config/environment.rb`, whose job is `Rails.application.initialize!`. After that, models, `Rails.logger`, credentials and database connections work as they do in the server. - The `before_initialize` hook sets `config.eager_load` from **`config.rake_eager_load`**, which defaults to `false`. Rake tasks therefore do not eager load, even in production where the server does. Classes load lazily, on first reference. - Like any Rake prerequisite, it runs **once per process**: a task chain where several tasks list `:environment` boots the app a single time. | Without `:environment` | With `:environment` | |---|---| | `Customer` raises `NameError` (no autoloading yet) | `Customer` autoloads | | no database connection configured | connections from `database.yml` | | initializers not run | initializers and `config/environments/*.rb` applied | | fast, fine for tasks that only shell out or touch files | needed for anything that touches app code | ## Consequences of no eager loading Most tasks never notice. The ones that do: - **Reflection over classes**: `ApplicationRecord.descendants` lists only models already referenced, so a task that loops over "every model" silently skips some. Call `Rails.application.eager_load!` first, or set `config.rake_eager_load = true` if many tasks need it. - **Boot time**: the flip side is that short tasks start faster, which is why lazy loading is the default for Rake. ## Adding arguments Rake's argument syntax combines with the prerequisite by moving it into a hash: ```ruby namespace :loyalty do desc "Recompute loyalty points for one store (bin/rails 'loyalty:recompute[42]')" task :recompute, [:store_id] => :environment do |_task, args| store = Store.find(args.fetch(:store_id)) Loyalty::Recalculator.new(store:).call end end ``` Points that trip people up in a Rails app: - The prerequisite **must** go in that hash; `task :recompute, [:store_id], :environment` does not declare it. - Arguments arrive as **strings**, so cast before using them as numbers or dates. - Call it as `bin/rails "loyalty:recompute[42]"`. In **zsh**, the default macOS shell, unquoted square brackets are a glob pattern and the command fails with `no matches found`. - For many options, environment variables (`STORE_ID=42 bin/rails loyalty:recompute`) read more clearly and need no quoting; how the two styles compare is a Rake question in its own right. ## Choosing the environment The Rails environment for the boot comes from `RAILS_ENV` (then `RACK_ENV`, then development), read when `:environment` initializes the app. Rake tasks have no `-e` flag, so the form is `RAILS_ENV=production bin/rails "loyalty:recompute[42]"`. ## Tasks that do not need the app Not every task should depend on `:environment`. A task that only shells out, cleans files or prints help boots faster without it. Rails' own `tmp:clear` and `log:clear` do not depend on it, while `app:template` does. Ask one question: does the body reference application code, configuration or the database? If yes, add `:environment`; if no, leave it off and keep the task quick. ## Debugging a task that cannot see a model 1. Check the declaration: is `:environment` really a prerequisite, in the hash form when arguments are present? 2. Check the environment: `RAILS_ENV` decides which `database.yml` entry and credentials are used. 3. Check eager loading: if the code reflects over classes, it may need `Rails.application.eager_load!`. 4. Check the file location: only `lib/tasks/**/*.rake` is loaded by the `Rakefile`.
- Why might ApplicationRecord.descendants miss models inside a production Rake task when it is complete in the production console?The production console boots with the environment's `eager_load = true`, so every model is loaded up front. Rake's environment task replaces that with `config.rake_eager_load`, false by default, so only models already referenced have been autoloaded. Call `Rails.application.eager_load!` in the task, or set `config.rake_eager_load = true`.
- What happens if you write task :recompute, [:store_id], :environment instead of the hash form?Rake does not read the third argument as a prerequisite, so the environment task never runs before the body. The first reference to `Store` then fails with `NameError` because the app was never initialized. Prerequisites go in the hash, `[:store_id] => :environment`, when arguments are declared.
- The Rakefile alone initializes the app, so :environment is optional
- Rake tasks eager load in production just like the server
- Task arguments arrive already cast to integers
- bin/rails loyalty:recompute[42] needs no quoting in zsh
- The environment task re-boots the app for every task that lists it
- bin/rails loyalty:recompute -e production runs the task in production