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?
answer
- subclass, loaded during boot
- initializer with before:/after:
- config namespace via OrderedOptions
- rake_tasks and generators blocks
- no app/ tree: that is an engine
basics
~20 sA 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 sA 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# 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
endgo deeper
Know that a gem hooks into Rails boot by subclassing Rails::Railtie, and that an engine is the bigger version with app/ code.
List what a railtie registers: initializers with before:/after:, a config namespace, middleware, rake_tasks, generators and console blocks.
Keep class bodies declarative, do work in initializers or load hooks, and confirm placement with bin/rails initializers and bin/rails middleware.
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