With `ActiveSupport.on_load(:active_record)`, when does the block run, what is `self` inside it, and how does a gem publish its own hook?
answer
- run_load_hooks at the class's last line
- class_eval on the loaded class
- late registration runs immediately
- yield: true and run_once: true
- :action_controller fires twice
basics
~10 sThe block runs when ActiveRecord::Base finishes loading and calls run_load_hooks(:active_record, Base), or immediately if that already happened; it is class_eval'd, so self is ActiveRecord::Base. A gem publishes a hook by calling ActiveSupport.run_load_hooks(:name, self) itself.
solid answer
~40 s`ActiveSupport.on_load(name)` stores a block under a hook name. The last line of `ActiveRecord::Base` is `ActiveSupport.run_load_hooks(:active_record, Base)`, which runs every stored block with `class_eval` on that class, so `self` is `ActiveRecord::Base` and `include AuditTrail::Model` applies to every model. A block registered after the hook has fired runs immediately. Options: `yield: true` passes the class as a block argument instead, and `run_once: true` keeps the block from running twice. Some names fire for more than one class: `:action_controller` runs for both `ActionController::Base` and `ActionController::API`, while `:action_controller_base` runs only for the former. A gem offers the same extension point by ending its class with `ActiveSupport.run_load_hooks(:audit_trail_entry, self)`.
code
ruby · 10 lines# lib/audit_trail/railtie.rb
initializer "audit_trail.controller" do
ActiveSupport.on_load(:action_controller_base) do
include AuditTrail::ControllerActor # self is ActionController::Base
end
ActiveSupport.on_load(:active_record, yield: true) do |base|
base.include AuditTrail::Model
end
endgo deeper
Remember that on_load(:active_record) waits until ActiveRecord::Base exists and then runs the block against it.
Explain run_load_hooks, class_eval versus yield: true, immediate execution for late registration, and run_once.
Pick precise hook names such as :action_controller_base, and publish run_load_hooks in your own gem classes so others can extend them lazily.
Make lazy extension points part of a gem's API, so host apps never need to load the gem's classes during boot.
## The two calls `ActiveSupport` extends `ActiveSupport::LazyLoadHooks`, which provides two methods: - **`on_load(name, options = {}, &block)`** stores a block under a hook name, for example `:active_record`. - **`run_load_hooks(name, base = Object)`** records `base` as loaded for that name and runs every stored block against it. Frameworks call `run_load_hooks` at the end of their main classes. `ActiveRecord::Base` ends with `ActiveSupport.run_load_hooks(:active_record, Base)`; `ActiveJob::Base` with `:active_job`; `ActionView::Base` with `:action_view`; `ActionMailer::Base` with `:action_mailer`. Anyone who wants to change those classes registers a block with `on_load` and lets the framework decide when the class exists. ## When the block runs 1. **Registered before the class loads:** the block waits. It runs when the class's last line calls `run_load_hooks`, which in development may be the first time a model is used. 2. **Registered after the class loaded:** `on_load` runs the block immediately for every base already recorded under that name. That second rule is what makes nested hooks work. The Active Support source shows Action Text registering inside one hook for a class from another framework: ```ruby ActiveSupport.on_load(:action_controller_base) do ActiveSupport.on_load(:action_text_content) do self.default_renderer = Class.new(ActionController::Base).renderer end end ``` ## What `self` is | Registration | How the block runs | `self` inside | |---|---|---| | `on_load(:active_record) { ... }` | `base.class_eval(&block)` | `ActiveRecord::Base` | | `on_load(:active_record, yield: true) { \|base\| ... }` | `block.call(base)` | whatever it was where the block was written; the class is `base` | | base is not a Module | `base.instance_eval(&block)` | that object | Because of `class_eval`, calls such as `include`, `prepend`, `extend` and `self.some_setting = value` act on the framework class directly. With `yield: true` the block stays in the caller's context, useful when it needs the caller's local methods. `run_once: true` records the block and skips it on later runs. It matters for hooks that fire more than once. ## Hooks that fire for several classes Some names are shared on purpose: - `ActionController::Base` calls `run_load_hooks(:action_controller_base, self)` and then `run_load_hooks(:action_controller, self)`; - `ActionController::API` calls `:action_controller_api` and then `:action_controller`. A block registered for `:action_controller` therefore runs once for each of the two classes. If a gem's module only makes sense for HTML controllers, register on `:action_controller_base`; if it must run once for whichever loads first, add `run_once: true`. ## Publishing a hook from a gem The audit-trail gem can give hosts and other gems the same lazy extension point for its own classes: ```ruby module AuditTrail class Entry < ActiveRecord::Base # ... ActiveSupport.run_load_hooks(:audit_trail_entry, self) end end ``` A host then writes `ActiveSupport.on_load(:audit_trail_entry) { belongs_to :tenant }` in an initializer without loading `AuditTrail::Entry`, which is itself an Active Record model and would load `ActiveRecord::Base`. Choose a name prefixed with the gem's name, because hook names are global. ## Choosing the hook for a job | You want to | Hook name | Fires for | |---|---|---| | Add a concern to every model | `:active_record` | `ActiveRecord::Base` | | Add a helper method to HTML controllers only | `:action_controller_base` | `ActionController::Base` | | Change every controller, HTML and API | `:action_controller` | both controller bases | | Add a view helper module | `:action_view` | `ActionView::Base` | | Configure every job | `:active_job` | `ActiveJob::Base` | | Extend every test case | `:active_support_test_case` | `ActiveSupport::TestCase` | Picking the narrowest hook keeps a gem from loading or altering classes it does not need. ## Misreadings to avoid - `on_load` does not load anything. It never triggers the class to load; it only waits. - It is not a per-request or per-reload callback; each block runs once per recorded base unless the base is loaded again. - The hook name is not derived from the class name automatically. It is whatever the framework passes to `run_load_hooks`, which is why the configuring guide keeps a table of available hooks, from `:action_cable_channel` to `:active_support_test_case`.
- A gem registers on_load(:active_record) after ActiveRecord::Base has already loaded. Does the block still run?Yes, immediately. `on_load` first runs the block for every base already recorded under that name, then stores it for any future `run_load_hooks` calls with the same name.
- Why does a block registered with on_load(:action_controller) run twice in an app that loads both controller bases?Both `ActionController::Base` and `ActionController::API` call `run_load_hooks(:action_controller, self)` at the end of their definitions. Use `:action_controller_base` or `:action_controller_api` to target one, or `run_once: true` to run once overall.
- on_load loads ActiveRecord::Base so the block can run
- A block registered after the class loaded is silently ignored
- self inside an on_load(:active_record) block is the gem's railtie
- :action_controller runs only for ActionController::Base
- Hook names are generated from class names automatically