Write Software, Well

How Rails Configures Zeitwerk

If you're curious how Rails uses and configures Zeitwerk, here's a highly simplified version of the Rails codebase that does what we just did.

The Autoloaders class sets up a Zeitwerk loader. The autoload paths are managed by the Rails.autoloaders.main autoloader.

# railties/lib/rails/autoloaders.rb

module Rails
class Autoloaders
def initialize
require "zeitwerk"

@main = Zeitwerk::Loader.new
end
end
end

The Finisher module adds an initializer that adds the configured directories to the Zeitwerk loader.

# railties/lib/rails/application/finisher.rb

module Rails
class Application
module Finisher
initializer :setup_main_autoloader do
autoloader = Rails.autoloaders.main

autoload_paths.uniq.each do |path|
autoloader.push_dir(path)
end

autoloader.setup
end
end
end
end