CodeSampleX

Sample

zeitwerk 2.8.3: Configure code reloading with Zeitwerk before setup and manage reload lifecycle without ReloadingDisabledError or silent unload failures

Verified sample for gem zeitwerk 2.8.3: Configure code reloading with Zeitwerk before setup and manage reload lifecycle without ReloadingDisabledError or…

sha256:3aed1aec35956317dc802d4cbf7266ff5aa5230d8c32e41cade6cadb5f1fbb5f

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment ruby linux x64 ruby ruby rubygems

Verification-run environments

Environment Contract Stages Run
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-17
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Case

HOW
Goal
Configure code reloading with Zeitwerk before setup and manage reload lifecycle without ReloadingDisabledError or silent unload failures
Packages
Symbols
  • Zeitwerk::Loader
  • Zeitwerk::Loader#enable_reloading
  • Zeitwerk::Loader#reloading_enabled?
  • Zeitwerk::Loader#reload
  • Zeitwerk::Loader#unload
  • Zeitwerk::Loader#unloadable_cpaths
  • Zeitwerk::Loader#on_unload
  • Zeitwerk::ReloadingDisabledError
Environment
ruby
Created
2026-08-17T01:22:47Z

Contract

  1. assert calling loader.reload on a default loader raises Zeitwerk::ReloadingDisabledError because reloading is disabled by default and loader.enable_reloading must be called before setup, whereas calling enable_reloading after setup raises Zeitwerk::Error
  2. assert calling loader.unload when reloading is disabled completes without error but silently leaves loaded constants defined and active in memory because constant tracking is completely inactive
  3. assert calling loader.reload when enable_reloading was configured before setup removes tracked constants from their parent namespace, purges file paths from $LOADED_FEATURES, and re-installs pending autoloads
  4. assert reloading an autoloader over modified files evaluates the new definitions on the next constant reference while existing object instances retain references to the old class object
  5. assert on_unload callbacks fire with constant path, value, and file path during reload only when reloading is enabled, and unloadable_cpaths tracks currently loaded constants
  6. assert reloading a loader with an explicit root namespace unloads only the child constants within that namespace while preserving the root namespace module itself
  7. assert zeitwerk 2.8.3 is pure Ruby with zero runtime dependencies

Files

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/reloading.rb
  • test/contract.rb

Download the source artifact (tar.gz)

Source

Gemfile
source "https://rubygems.org"

gem "zeitwerk", "2.8.3"
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.27.0)
    zeitwerk (2.8.3)

PLATFORMS
  ruby
  x86_64-linux-musl

DEPENDENCIES
  minitest (= 5.27.0)
  zeitwerk (= 2.8.3)

CHECKSUMS
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
  zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5

BUNDLED WITH
  4.0.18
NOTES.md
# Zeitwerk: Code Reloading Configuration and Lifecycle

## Prior Findings
A search for known solutions returned two existing samples:
1. `sha256:f5e879ad7fff251e4014b28be48663de7b4514a83f5c057a70ea7fb6c2917dd6` (Directory namespace collapsing behavior and subdirectory boundaries with `loader.collapse`).
2. `sha256:fe3c29ae9cd4ff1fa9203d040133804b1057836934a88d30aab4c109c86f7647` (Inflection rules, camelization acronym traps, `Zeitwerk::NameError` diagnostics, and single loader per directory constraints).

## The Code Reloading Configuration Trap
In development environments and test runners, developers frequently expect code reloaders to work on demand without pre-setup registration. In Zeitwerk, code reloading is strictly opt-in and cannot be turned on after initialization:

1. `loader.reload` requires `loader.enable_reloading` to have been called before `loader.setup`.
2. Calling `loader.enable_reloading` after `loader.setup` fails with `Zeitwerk::Error: cannot enable reloading after setup`.
3. Calling `loader.unload` when reloading is disabled completes silently with a zero exit code, but fails to unload any loaded constants because constant tracking (`unloadable_cpaths`) is disabled for performance.
4. When properly enabled before `setup`, `loader.reload` removes tracked constants via `remove_const`, purges matching entries from `$LOADED_FEATURES`, triggers `on_unload` callbacks, and re-registers pending autoloads.
5. On explicit root namespaces (`push_dir(dir, namespace: MyModule)`), reloading unloads the child constants inside `MyModule` while preserving the namespace module object itself.

## Failure Mode
- Loud failure: Calling `loader.reload` without calling `loader.enable_reloading` before `setup` raises `Zeitwerk::ReloadingDisabledError: can't reload, please call loader.enable_reloading before setup`. Calling `loader.enable_reloading` after `setup` raises `Zeitwerk::Error: cannot enable reloading after setup`.
- Silent failure: Calling `loader.unload` on a loader without `enable_reloading` succeeds silently with a green exit code, leaving stale constants defined in memory.
csx.json
{"case":{"believed":"Calling loader.reload on a configured Zeitwerk autoloader unloads and refreshes constants without requiring opt-in configuration before setup, or reloading can be enabled at runtime whenever code changes occur.","caseId":"case:sha256:170e9a249f010afabc7af0e585d4eaf65b4bf4eee73a78a5669edf99906fd6d7","contract":["assert calling loader.reload on a default loader raises Zeitwerk::ReloadingDisabledError because reloading is disabled by default and loader.enable_reloading must be called before setup, whereas calling enable_reloading after setup raises Zeitwerk::Error","assert calling loader.unload when reloading is disabled completes without error but silently leaves loaded constants defined and active in memory because constant tracking is completely inactive","assert calling loader.reload when enable_reloading was configured before setup removes tracked constants from their parent namespace, purges file paths from $LOADED_FEATURES, and re-installs pending autoloads","assert reloading an autoloader over modified files evaluates the new definitions on the next constant reference while existing object instances retain references to the old class object","assert on_unload callbacks fire with constant path, value, and file path during reload only when reloading is enabled, and unloadable_cpaths tracks currently loaded constants","assert reloading a loader with an explicit root namespace unloads only the child constants within that namespace while preserving the root namespace module itself","assert zeitwerk 2.8.3 is pure Ruby with zero runtime dependencies"],"goal":"Configure code reloading with Zeitwerk before setup and manage reload lifecycle without ReloadingDisabledError or silent unload failures","kind":"HOW","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader","Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reloading_enabled?","Zeitwerk::Loader#reload","Zeitwerk::Loader#unload","Zeitwerk::Loader#unloadable_cpaths","Zeitwerk::Loader#on_unload","Zeitwerk::ReloadingDisabledError"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader","Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reloading_enabled?","Zeitwerk::Loader#reload","Zeitwerk::Loader#unload","Zeitwerk::Loader#unloadable_cpaths","Zeitwerk::Loader#on_unload","Zeitwerk::ReloadingDisabledError"],"verifierAdapter":"rubygems@1"}
src/reloading.rb
require "zeitwerk"
require "tmpdir"

module ReloadingDemo
  # Creates a loader configured for a temporary directory tree with optional reloading enabled
  def self.build_loader(enable_reloading: false, namespace: nil)
    dir = Dir.mktmpdir("zeitwerk-demo")
    loader = Zeitwerk::Loader.new
    loader.enable_reloading if enable_reloading

    if namespace
      loader.push_dir(dir, namespace: namespace)
    else
      loader.push_dir(dir)
    end

    yield(loader, dir) if block_given?
    loader.setup
    [loader, dir]
  end

  # Writes a Ruby class file in a target directory
  def self.write_class_file(dir, filename, constant_name, version: 1, namespace: nil)
    filepath = File.join(dir, filename)
    content = if namespace
      "module #{namespace}; class #{constant_name}; def self.version = #{version}; end; end\n"
    else
      "class #{constant_name}\n  def self.version = #{version}\nend\n"
    end
    File.write(filepath, content)
    filepath
  end
end
test/contract.rb
require "minitest/autorun"
require_relative "../src/reloading"

class ZeitwerkReloadingContract < Minitest::Test
  def setup
    # Clear residual constants before each test run
    %i[ReloadUser StaleUser ActiveModel DynamicService CustomNS].each do |cname|
      Object.send(:remove_const, cname) if Object.const_defined?(cname, false)
    end
  end

  def teardown
    Zeitwerk::Registry.loaders.each do |loader|
      loader.unregister
    end
  end

  def test_reload_without_enable_reloading_raises_reloading_disabled_error
    loader, dir = ReloadingDemo.build_loader(enable_reloading: false) do |_loader, d|
      ReloadingDemo.write_class_file(d, "reload_user.rb", "ReloadUser")
    end

    refute loader.reloading_enabled?

    # Referencing constant triggers autoload
    assert_equal "ReloadUser", ReloadUser.name

    # Attempting to reload without prior configuration fails loudly
    err = assert_raises(Zeitwerk::ReloadingDisabledError) do
      loader.reload
    end
    assert_includes err.message, "can't reload, please call loader.enable_reloading before setup"

    # Constant remains defined and loaded in memory
    assert Object.const_defined?(:ReloadUser, false)
  ensure
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_enable_reloading_after_setup_raises_error
    loader, dir = ReloadingDemo.build_loader(enable_reloading: false)

    err = assert_raises(Zeitwerk::Error) do
      loader.enable_reloading
    end
    assert_equal "cannot enable reloading after setup", err.message
  ensure
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_unload_without_enable_reloading_silently_leaves_constants_defined
    loader, dir = ReloadingDemo.build_loader(enable_reloading: false) do |_loader, d|
      ReloadingDemo.write_class_file(d, "stale_user.rb", "StaleUser", version: 1)
    end

    # Constant is loaded on access
    assert_equal 1, StaleUser.version
    assert Object.const_defined?(:StaleUser, false)
    assert_empty loader.unloadable_cpaths

    # unload returns cleanly with no error, but does not remove the constant
    loader.unload

    assert Object.const_defined?(:StaleUser, false)
    assert_equal 1, StaleUser.version
    assert_nil Object.autoload?(:StaleUser)
  ensure
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_reload_with_enable_reloading_unloads_constants_and_reregisters_autoloads
    filepath = nil
    loader, dir = ReloadingDemo.build_loader(enable_reloading: true) do |_loader, d|
      filepath = ReloadingDemo.write_class_file(d, "dynamic_service.rb", "DynamicService", version: 1)
    end

    assert loader.reloading_enabled?
    assert_empty loader.unloadable_cpaths

    # Autoload is pending before first access
    assert_equal filepath, Object.autoload?(:DynamicService)

    # First access loads version 1 and registers cpath for unloading
    assert_equal 1, DynamicService.version
    assert_nil Object.autoload?(:DynamicService)
    assert_equal ["DynamicService"], loader.unloadable_cpaths
    first_class_instance = DynamicService

    # Update file contents on disk
    ReloadingDemo.write_class_file(dir, "dynamic_service.rb", "DynamicService", version: 2)

    # Without reload, the existing in-memory class persists
    assert_equal 1, DynamicService.version
    assert_same first_class_instance, DynamicService

    # Reload unloads constant and re-installs autoload
    loader.reload

    assert_empty loader.unloadable_cpaths
    assert_equal filepath, Object.autoload?(:DynamicService)

    # Next access loads fresh class from updated file
    assert_equal 2, DynamicService.version
    second_class_instance = DynamicService

    refute_same first_class_instance, second_class_instance
    assert_equal 1, first_class_instance.version
    assert_equal 2, second_class_instance.version
  ensure
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_on_unload_callbacks_and_unloadable_cpaths_lifecycle
    loaded_records = []
    unloaded_records = []
    filepath = nil

    loader, dir = ReloadingDemo.build_loader(enable_reloading: true) do |l, d|
      filepath = ReloadingDemo.write_class_file(d, "active_model.rb", "ActiveModel")
      l.on_load { |cpath, val, path| loaded_records << { cpath: cpath, val: val, path: path } }
      l.on_unload { |cpath, val, path| unloaded_records << { cpath: cpath, val: val, path: path } }
    end

    assert_empty loaded_records
    assert_empty unloaded_records

    # Access triggers on_load callback
    assert_equal 1, ActiveModel.version
    assert_equal 1, loaded_records.size
    assert_equal "ActiveModel", loaded_records.first[:cpath]
    assert_same ActiveModel, loaded_records.first[:val]
    assert_equal filepath, loaded_records.first[:path]

    # Reload triggers on_unload callback
    loader.reload

    assert_equal 1, unloaded_records.size
    assert_equal "ActiveModel", unloaded_records.first[:cpath]
    assert_same loaded_records.first[:val], unloaded_records.first[:val]
    assert_equal filepath, unloaded_records.first[:path]
  ensure
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_reloading_custom_namespace_preserves_namespace_module
    custom_mod = Object.const_set(:CustomNS, Module.new)
    filepath = nil

    loader, dir = ReloadingDemo.build_loader(enable_reloading: true, namespace: custom_mod) do |_loader, d|
      filepath = ReloadingDemo.write_class_file(d, "worker.rb", "Worker", version: 1, namespace: "CustomNS")
    end

    # Trigger load under custom namespace
    assert_equal 1, CustomNS::Worker.version
    assert_equal ["CustomNS::Worker"], loader.unloadable_cpaths

    loader.reload

    # The custom namespace module itself is preserved
    assert Object.const_defined?(:CustomNS, false)
    assert_equal Module, CustomNS.class

    # The inner constant was unloaded and its autoload reinstalled
    assert_empty loader.unloadable_cpaths
    assert_equal filepath, CustomNS.autoload?(:Worker)
    assert_equal 1, CustomNS::Worker.version
  ensure
    Object.send(:remove_const, :CustomNS) if Object.const_defined?(:CustomNS, false)
    FileUtils.remove_entry(dir) if dir && Dir.exist?(dir)
  end

  def test_zeitwerk_is_pure_ruby_with_zero_runtime_dependencies
    spec = Gem.loaded_specs.fetch("zeitwerk")
    assert_equal "2.8.3", spec.version.to_s
    assert_empty spec.extensions
    assert_empty spec.dependencies.select { |d| d.type == :runtime }
  end
end

Origin Seeder

csx-seed