skip to content

Railties & Load Hooks

A gem hooks into Rails through a Rails::Railtie with initializers, config namespaces and rake tasks, and defers framework patches with ActiveSupport.on_load. Interviewers probe what slows boot.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Ruby gem, what is a `Rails::Railtie` for, and what can an audit-trail gem's railtie register with the host Rails app?

level: middleimportance: must knowfreq 30%

answer

  1. subclass, loaded during boot
  2. initializer with before:/after:
  3. config namespace via OrderedOptions
  4. rake_tasks and generators blocks
  5. no app/ tree: that is an engine

basics

~20 s

A Rails::Railtie subclass is how a gem joins a host app's boot. Its class body can add initializers, a config namespace, middleware, rake tasks, generators and console, runner or server blocks; app/ code, routes and migrations need an engine.

solid answer

~30 s

A gem defines `AuditTrail::Railtie < Rails::Railtie` and requires it from `lib/audit_trail.rb`, often guarded with `if defined?(Rails::Railtie)` so the gem still works outside Rails. Defining the subclass registers it; Rails keeps one instance. The class body can declare `initializer "audit_trail.subscribe" do |app| ... end` blocks, ordered with `before:` and `after:`; add a config namespace with `config.audit_trail = ActiveSupport::OrderedOptions.new`; add middleware through `config.app_middleware`; set generator defaults through `config.app_generators`; and register `rake_tasks`, `generators`, `console`, `runner` and `server` blocks. It can also use the shared `config.before_initialize`, `config.after_initialize` and `config.to_prepare` hooks. A railtie has no `app/` paths, routes or migrations; those need `Rails::Engine`.

code

ruby · 19 lines
ruby
# lib/audit_trail/railtie.rb
module AuditTrail
  class Railtie < ::Rails::Railtie
    config.audit_trail = ActiveSupport::OrderedOptions.new
    config.audit_trail.enabled = true

    initializer "audit_trail.model" do
      ActiveSupport.on_load(:active_record) { include AuditTrail::Model }
    end

    rake_tasks do
      load "tasks/audit_trail.rake"
    end

    generators do
      require "generators/audit_trail/install_generator"
    end
  end
end

go deeper

for a junior

Know that a gem hooks into Rails boot by subclassing Rails::Railtie, and that an engine is the bigger version with app/ code.

for a middle

List what a railtie registers: initializers with before:/after:, a config namespace, middleware, rake_tasks, generators and console blocks.

for a senior

Keep class bodies declarative, do work in initializers or load hooks, and confirm placement with bin/rails initializers and bin/rails middleware.

for a principal

Choose railtie or engine by what the gem ships, and keep a gem's boot footprint small because every host pays for it.

## Why a gem needs a railtie A gem can be used in a Rails app without any Rails-specific code. It needs a **railtie** only when it must take part in the host's boot: register an initializer, expose configuration, add middleware or rake tasks, or subscribe to instrumentation. The `Rails::Railtie` documentation lists exactly those cases: creating initializers, configuring a framework such as generators, adding `config.*` keys, setting up an `ActiveSupport::Notifications` subscriber and adding rake tasks. ## Registering the railtie 1. Define a subclass, conventionally `MyNamespace::Railtie`, in `lib/audit_trail/railtie.rb`. 2. Require it from the gem's entry file. Rails' docs show `require "audit_trail/railtie" if defined?(Rails::Railtie)` so the gem can also load outside Rails; `rails plugin new audit_trail` writes an unconditional require. 3. The host's `Bundler.require` loads the gem from `config/application.rb`, the subclass is defined, and Rails records it. `Rails::Railtie` hides `new` and exposes a single `instance`. ## What the class body can declare | Declaration | What it adds to the host | |---|---| | `initializer "audit_trail.subscribe" do \|app\| ... end` | A boot step; the block may take the application object | | `initializer ..., before: :name` / `after: :name` | Places the step relative to another initializer | | `config.audit_trail = ActiveSupport::OrderedOptions.new` | A namespace the host can set in `config/application.rb` | | `config.app_middleware.use AuditTrail::RequestTagger` | Middleware replayed onto the host's stack | | `config.app_generators.orm :active_record` | Defaults for the host's generators unless the host overrides them | | `rake_tasks { load "tasks/audit_trail.rake" }` | Tasks visible in `bin/rails -T` | | `generators { require "generators/audit_trail/install_generator" }` | Generators loaded during generator lookup | | `console { ... }`, `runner { ... }`, `server { ... }` | Code run when those commands start | | `config.before_initialize`, `config.after_initialize`, `config.to_prepare` | Callbacks around the whole boot | Initializers are named; the convention is `"gem_name.what_it_does"`. Without `before:` or `after:` an initializer runs after the previous one declared in the same class, and railties contribute their initializers in load order, ahead of the application's own, which come last. ## Railtie or engine An **engine** is a railtie with paths: it adds `app/` directories to the autoloader, a route set, `config/locales`, `lib/tasks` and migrations. A **railtie** has none of those. A practical consequence: an engine loads its `lib/tasks/*.rake` automatically, while a plain railtie loads a task file only if a `rake_tasks` block does so. The `lib/tasks/audit_trail_tasks.rake` that the plugin generator writes for a railtie gem stays invisible to the host until the railtie registers it. ## The audit-trail gem in practice For a gem that records who changed which record, the railtie typically: - defines `config.audit_trail` with defaults such as `enabled` and `actor_method`; - adds an initializer that subscribes to the gem's own notifications and reads the host's settings; - includes its model concern into Active Record lazily with `ActiveSupport.on_load(:active_record)`, never by touching `ActiveRecord::Base` directly; - registers `rake_tasks` for a pruning task and a `generators` block for an install generator that writes the gem's migration and initializer. ## Seeing it from the host - `bin/rails initializers` prints every initializer in run order as `ClassName.initializer_name`, which shows where `AuditTrail::Railtie.audit_trail.subscribe` lands. - `bin/rails middleware` shows whether the gem's middleware was added and where. - `bin/rails -T` lists tasks registered through `rake_tasks`. ## Testing a railtie gem `rails plugin new audit_trail` writes a `test/dummy` application for railtie gems as well as engines, so the gem's tests can boot a real host: - assert that `Rails.application.config.audit_trail` exists with its defaults after boot; - assert that a model in the dummy app responds to the method the railtie's load hook includes; - run `bin/rails initializers` inside the gem directory to see where the gem's initializers fall; - boot the dummy app with a setting overridden in its `config/application.rb` and check the gem honours it. ## Common mistakes - Calling a railtie `MyGem::Engine` and subclassing `Rails::Engine` when no `app/` code exists, which adds autoload paths and an empty route set for nothing. - Doing work at class-body time that belongs in an initializer: the class body runs when the gem is required, before the host has configured anything. - Touching framework classes directly instead of through load hooks, which loads them during boot. - Using generic initializer names that collide in `before:` and `after:` references.

  • Why might `bin/rails -T` not show a railtie gem's lib/tasks/audit_trail_tasks.rake?
    Only engines load `lib/tasks/*.rake` automatically. A plain `Rails::Railtie` runs just the blocks registered with `rake_tasks`, so the railtie needs `rake_tasks { load "tasks/audit_trail_tasks.rake" }` (with the path resolvable from the gem's lib) for the host to see the task.
  • How does a railtie add middleware to the host app?
    Through `config.app_middleware`, for example `config.app_middleware.use AuditTrail::RequestTagger`, or inside an initializer with `app.middleware.use`. `app_middleware` records the operations and replays them on the application's stack once it is built.

  • A railtie is needed for any gem used in a Rails app
  • Railtie subclasses must be instantiated by the host with new
  • A railtie can add app/models and routes to the host
  • A railtie gem's lib/tasks files load automatically like an engine's
  • Initializers run in alphabetical order of their names
open as a page

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?

level: seniorimportance: must knowfreq 26%

basics

~20 s

Referencing 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.

open as a page

In a Rails 8.1 app's config/application.rb, what does `require "rails/all"` load, and how is a framework such as Action Cable left out?

level: juniorimportance: should knowfreq 30%

basics

~10 s

require "rails/all" requires each framework's railtie or engine, such as active_record/railtie and action_cable/engine, which registers its initializers and config namespace. An app without Action Cable requires frameworks one by one, leaving "action_cable/engine" commented out.

open as a page

In a `Rails::Railtie`, how does a gem expose `config.audit_trail` settings to the host, and why read them in an initializer rather than the class body?

level: middleimportance: should knowfreq 24%

basics

~20 s

The railtie assigns config.audit_trail = ActiveSupport::OrderedOptions.new, with defaults, and the host overrides keys in config/application.rb or an environment file. The class body runs when the gem is required, before host config exists, so values are read in an initializer.

open as a page

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?

level: middleimportance: should knowfreq 22%

basics

~10 s

The 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.

open as a page