Why is `ActiveRecord::Base.include(AuditTrail::Model)` in a gem's railtie initializer harmful, and how do you find which gem loads Active Record early?
answer
- constant reference loads the framework
- active_record.set_configs runs in on_load
- class-level values from config/initializers missed
- slower boot for every command
- on_load { puts caller } before Bundler.require
basics
~20 sReferencing ActiveRecord::Base during boot loads Active Record early, slowing every boot and running its load hooks before the app's config/initializers, so class-level config.active_record values set there are never copied. Use ActiveSupport.on_load(:active_record) and trace the loader.
solid answer
~40 sNaming `ActiveRecord::Base` in an initializer forces Ruby to load it, and with it most of Active Record, during boot. Every command pays for that, including tasks and test runs that never touch a model. Worse, Active Record's railtie copies `config.active_record.*` onto `ActiveRecord::Base` inside an `on_load(:active_record)` hook from its `active_record.set_configs` initializer. If a gem loads the class before the app's `config/initializers` run, that hook has already fired, so class-level settings placed there, such as `strict_loading_by_default`, never reach `ActiveRecord::Base`. The fix is `ActiveSupport.on_load(:active_record) { include AuditTrail::Model }`. To find an offender, register `ActiveSupport.on_load(:active_record) { puts caller }` in `config/application.rb` before `Bundler.require` and read the backtrace it prints.
code
ruby · 10 lines# config/application.rb (temporary probe)
require_relative "boot"
require "rails/all"
ActiveSupport.on_load(:active_record) do
warn "ActiveRecord::Base loaded from:"
warn caller.grep_v(%r{/active_support/lazy_load_hooks}).first(15)
end
Bundler.require(*Rails.groups)go deeper
Know that gems should wrap framework changes in ActiveSupport.on_load instead of naming ActiveRecord::Base directly.
Explain how set_configs copies config.active_record inside an on_load hook, and why values from config/initializers miss it.
Diagnose an ignored upgrade default or a slow boot by tracing the first load with an early on_load probe, then fix the gem or report it upstream.
Set a boot budget and audit gems for early framework loads as part of dependency review.
## What the innocent line does ```ruby initializer "audit_trail.model" do ActiveRecord::Base.include(AuditTrail::Model) end ``` Ruby must resolve the constant `ActiveRecord::Base`, so it requires `active_record/base` and everything it pulls in. The configuring guide spells out the cost: loading a framework class prematurely loads the entire framework at boot, which can slow boot time and conflict with the load order Rails manages. The **load contract** is that Rails decides when framework classes load and others hook in with `ActiveSupport.on_load`. ## Effect 1: slower boot everywhere Without the early reference, `ActiveRecord::Base` loads when something needs it: eager loading in production, or the first model touched in development and test. With it, every process pays at boot: `bin/rails routes`, a rake task that only reads a file, a test file that tests a plain Ruby object. A single such line adds Active Record's load time to every command a team runs. ## Effect 2: configuration silently ignored Active Record's railtie applies settings in two places inside its `active_record.set_configs` initializer: - an `ActiveSupport.on_load(:active_record)` block copies every `config.active_record.*` key onto `ActiveRecord::Base` (or onto the `ActiveRecord` module where a module-level setter exists); - a `config.after_initialize` block copies module-level settings again at the end of boot. The load hook runs exactly once, when `ActiveRecord::Base` finishes loading. Consider the order in a typical host: 1. `rails/all` defines `ActiveRecord::Railtie`, so its initializers come before the gem's. 2. The gem's initializer references `ActiveRecord::Base`; the class loads and the `set_configs` hook copies the configuration **as it is at that moment**: `config/application.rb` and the environment file. 3. The app's `config/initializers` run afterwards. A line such as `Rails.application.config.active_record.strict_loading_by_default = true` updates the config object, but the hook that copies it onto `ActiveRecord::Base` has already run. The result is a setting that is visible in `Rails.application.config` and has no effect on models, which is very hard to spot during an upgrade. Settings that live on the `ActiveRecord` module itself, such as `raise_on_missing_required_finder_order_columns`, are copied again by the `after_initialize` block and survive; class-level settings on `ActiveRecord::Base`, such as `strict_loading_by_default`, do not. ## The fix ```ruby initializer "audit_trail.model" do ActiveSupport.on_load(:active_record) do include AuditTrail::Model end end ``` The same applies to every framework class: | Direct reference at boot | Deferred form | |---|---| | `ActiveRecord::Base.include(M)` | `ActiveSupport.on_load(:active_record) { include M }` | | `ActionController::Base.prepend(M)` | `ActiveSupport.on_load(:action_controller_base) { prepend M }` | | `ActiveJob::Base.queue_adapter = ...` | set `config.active_job.queue_adapter` instead | | `ActionMailer::Base.include(M)` | `ActiveSupport.on_load(:action_mailer) { include M }` | Watch for indirect references too: - a gem model `class AuditTrail::Entry < ActiveRecord::Base` that the railtie references at boot; - `ActiveRecord::Base.connection` calls to check a table in an initializer; - constants such as `ActiveRecord::Base::SOMETHING` used as defaults in a config class body. ## Finding the gem that loads it 1. **Print the loader's backtrace.** In `config/application.rb`, after `require "rails/all"` and before `Bundler.require`, add `ActiveSupport.on_load(:active_record) { puts caller }`. Registered that early, it runs when `ActiveRecord::Base` loads and the backtrace names the file that referenced it. Do the same for `:action_controller_base` or `:active_job` when those are suspect. 2. **Check whether it is loaded.** In an initializer at the end of `config/initializers`, test `$LOADED_FEATURES.grep(%r{active_record/base\.rb})` to see whether the class was already loaded during boot. 3. **Read the order.** `bin/rails initializers` lists each initializer as `ClassName.initializer_name`; the gem initializer just before the load is the usual suspect. 4. **Measure.** Time `bin/rails runner "nil"` before and after the fix. Remove the probes after use; they print on every boot. ## Prevention for gem authors - Never name a framework class in a railtie's class body or initializer; register an `on_load` block instead. - Keep the gem's own models out of the boot path, and publish `ActiveSupport.run_load_hooks(:audit_trail_entry, self)` so hosts can extend them lazily. - Add a test that boots a dummy app and asserts the framework class is not loaded after initialization.
- Does a setting in config/application.rb survive an early load?Usually yes: the application class body and environment files are evaluated before railtie initializers run, so the copy made when the class loads already includes them. Values set in config/initializers are the ones at risk.
- Why is the ignored-setting effect so hard to catch?The value is present in `Rails.application.config.active_record`, so inspecting the config shows it as set. Only `ActiveRecord::Base.strict_loading_by_default` (or whichever class-level attribute it is) reveals the old value, and only for settings assigned from `config/initializers`; module-level ones are copied again after initialization.
- Referencing ActiveRecord::Base is free because Rails autoloads it lazily
- config.active_record values are read every time a model is used
- on_load(:active_record) forces Active Record to load at boot
- Early loading only matters in development
- Every config.active_record setting is ignored after an early load