Skip to content
RY

What Is a Railtie? The Hook Every Rails Component (and Every Gem) Uses to Join the Party

Ram Laxman Yadav7 min read

You add gem "some_gem" to your Gemfile, run bundle install, and a new config option just works — config.some_gem.something = true, a rake task you never wrote, a setting your own app never defined. No glue code, no setup guide, no initializer you had to copy-paste from a README. It just appears.

A Railtie is almost always how. It’s the single most-used, least-explained piece of Rails’ own plumbing — every official component is built with one (Active Record, Action Cable, all of them), and so is nearly every gem that’s ever hooked into how your app boots. This post is the explanation most of those README snippets skip.

1. What a Railtie actually is, in one sentence

A Rails::Railtie is a plain Ruby class that lets a library register itself with a booting Rails application — initializer code to run, config options to expose, rake tasks to load, generators to offer — without that application needing to know the library exists in advance.

That last part is the whole point. Rails doesn’t maintain a master list of “here’s every gem that might want to hook into boot.” Instead, any gem can define a class, inherit from Rails::Railtie, and from that moment on, it’s part of the same discovery-and-run machinery that Rails uses for its own built-in components. There’s no special-casing — a third-party gem’s Railtie and ActiveRecord::Railtie are discovered and run exactly the same way.

2. How a Railtie actually gets found and run

This is the part most explanations skip, and it’s the genuinely clever bit: there’s no registration call to make. The moment your class statement finishes executing — class Railtie < Rails::Railtie — it’s already registered. Rails::Railtie defines an inherited hook that Ruby calls automatically whenever anything subclasses it, and that hook is what quietly adds your class to Rails’ internal list of known Railties. You never call anything like Rails.register(MyRailtie) — subclassing is the registration.

Gemfile

gem "my_gem" is listed

config/application.rb

Bundler.require(*Rails.groups) actually requires my_gem

lib/my_gem.rb

requires my_gem/railtie — the gem’s own entry point

class Railtie < Rails::Railtie

Ruby’s inherited hook fires the instant this line runs — your class is now in Rails’ Railtie registry, with zero explicit registration call

Rails.application.initialize!

run_initializers walks every known Railtie (yours included), topologically sorts all their initializer blocks together, and runs them

Note

This is also exactly why a Railtie’s file has to be required before Rails.application.initialize! runs — which Bundler.require(*Rails.groups) guarantees, since it runs earlier in config/application.rb. A Rails::Railtie subclass defined after initialize! has already walked the registry simply shows up too late to be included in that boot’s initializer run.

3. Building one: a real, working example

Let’s build a small gem called request_id_logger — its job is to tag every log line in a request with a request ID, and to expose a config option for which header to read that ID from. This is a genuinely common real-world Railtie use case: wiring in a piece of Rack middleware, plus a config namespace to control it.

The file structure a gem like this follows:

request_id_logger/
├── lib/
│ ├── request_id_logger.rb # entry point
│ └── request_id_logger/
│ ├── railtie.rb # the Railtie itself
│ ├── middleware.rb # the actual Rack middleware
│ └── tasks/request_id_logger.rake
└── request_id_logger.gemspec

lib/request_id_logger.rb — the entry point, which conditionally requires the Railtie:

require "request_id_logger/middleware"
module RequestIdLogger
# Guarded so this gem still loads cleanly in a plain Ruby script,
# not just inside a Rails app.
require "request_id_logger/railtie" if defined?(Rails::Railtie)
end

lib/request_id_logger/railtie.rb — this is the whole point of the post:

module RequestIdLogger
class Railtie < Rails::Railtie
# Namespaces a config option under `config.request_id_logger`,
# with a sensible default — this is what lets a host app write
# `config.request_id_logger.header = "X-My-Custom-Id"` in its own
# config/application.rb, as if it were a built-in Rails setting.
config.request_id_logger = ActiveSupport::OrderedOptions.new
config.request_id_logger.header = "X-Request-Id"
# Runs during the app's own boot — `app` here is the actual
# Rails::Application instance, so `app.middleware` is the same
# middleware stack your own config/application.rb can modify.
initializer "request_id_logger.insert_middleware" do |app|
app.middleware.use RequestIdLogger::Middleware, header: app.config.request_id_logger.header
end
# Exposes `rails request_id_logger:report` without the host app
# needing to know this task exists anywhere in its own codebase.
rake_tasks do
load File.expand_path("tasks/request_id_logger.rake", __dir__)
end
# Skip inserting middleware in `rails console` — there's no
# request/response cycle there for it to do anything useful with.
console do |app|
app.config.request_id_logger.header = nil
end
end
end

And from inside any app that just added gem "request_id_logger" to its Gemfile, this now works with no further setup:

# config/application.rb, in the host app — not the gem
config.request_id_logger.header = "X-Correlation-Id"

Nobody on the host app’s team had to read the gem’s source to know that line would work. config.request_id_logger existing at all, and doing something meaningful when set, is entirely the Railtie’s doing.

Warning

One genuinely easy mistake: writing config.request_id_logger.header = ... inside the Railtie’s own initializer block, instead of as a direct class-body assignment the way the example above does it. Initializers run in whatever order the topological sort puts them in — there’s no guarantee a host app’s own config.request_id_logger.header = "X-Correlation-Id" (set directly in config/application.rb, which always runs before initialize!) would survive being overwritten by your own initializer running after it. Setting the default value at the class level, outside any initializer block, is what makes it safely overridable.

4. Railtie vs. Engine — the difference that actually matters

Every Rails::Engine is built on top of Rails::Railtie — an Engine is a Railtie, plus a lot more. The guide’s own framing is worth repeating because it’s the cleanest version of this distinction: a Railtie is “the most basic integration point for extending Rails” and doesn’t expose any controllers, views, or models — an Engine “behaves like a mini Rails application,” with its own routes, controllers, views, and even assets.

Rails::Railtie

Hooks into boot. Nothing more.

  • ✓ initializer blocks
  • ✓ config.* namespacing
  • ✓ rake_tasks
  • ✓ generators, console blocks
  • ✗ No routes, controllers, or views
  • ✗ No isolated namespace

Rails::Engine

Everything a Railtie does, plus its own mini-app.

  • ✓ Everything in Railtie
  • ✓ Its own app/ (models, views, controllers)
  • ✓ Its own config/routes.rb, mountable
  • ✓ isolate_namespace to avoid class-name clashes with the host app

The practical rule of thumb: if you’re exposing configuration, hooking into boot, or shipping a rake task, you want a Railtie. The moment you need your own controller, your own view, or a /mounted_at route namespace that doesn’t collide with the host app’s own classes, you’ve crossed into Engine territory — which is why generating a new plugin with rails plugin new my_gem --mountable gives you namespace isolation and an Engine class in lib/my_gem/engine.rb, instead of a bare Railtie.

5. What Rails actually requires of you to make this work

There’s remarkably little:

  1. Load order, not registration. Your Rails::Railtie subclass just needs to be required before Rails.application.initialize! runs — normal Bundler.require timing handles this for any gem in your Gemfile automatically.
  2. A defensive require guard, so the same gem doesn’t explode when used outside Rails: require "my_gem/railtie" if defined?(Rails::Railtie).
  3. Namespaced config, so your options don’t collide with anyone else’s: config.my_gem_name = ActiveSupport::OrderedOptions.new, never bare top-level config keys.
  4. Named initializers, since Rails needs a unique string to topologically sort against other gems’ initializers: initializer "my_gem.some_description" do |app| ... end.

Get new posts in your inbox

One email whenever I publish something new. No spam, unsubscribe anytime.

← Back to all posts