サンプル
zeitwerk 2.8.3: Configure root directories with Zeitwerk and handle default top-level Object namespace and directory-filtering defaults in push_dir and dirs without name collisions or missing constant errors
検証済みサンプル — gem zeitwerk 2.8.3: Configure root directories with Zeitwerk and handle default top-level Object namespace and directory-filtering defaults in…
sha256:3ebbd02c22c5e7760ba293cd6b0f6fa1467e5f31a76221f26d619502c4e54873
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 2
- ビルドした署名鍵
- 2
宣言された環境
ruby linux x64 ruby ruby rubygems
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| 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 |
ケース
HOW- ゴール
- Configure root directories with Zeitwerk and handle default top-level Object namespace and directory-filtering defaults in push_dir and dirs without name collisions or missing constant errors
- パッケージ
- シンボル
-
- Zeitwerk::Loader#push_dir
- Zeitwerk::Loader#dirs
- Zeitwerk::Loader#eager_load
- Zeitwerk::Loader#all_expected_cpaths
- Zeitwerk::Loader#cpath_expected_at
- 環境
- ruby
- 作成日
- 2026-08-17T02:49:39Z
コントラクト
- assert push_dir with namespace left unset defaults the root namespace to Object rather than inferring a namespace from the directory name, mapping the directory to Object in all_expected_cpaths and expecting unprefixed top-level constants
- assert a file that defines its class nested inside a directory-named module raises Zeitwerk::NameError under default push_dir because Zeitwerk expects the unprefixed top-level constant name
- assert scoping files under a custom parent module requires explicitly passing namespace: Module to push_dir, which expects prefixed constant paths and autovivifies subdirectories under that module
- assert push_dir validates the namespace argument strictly, rejecting strings, symbols, and anonymous modules with Zeitwerk::Error
- assert loader.dirs with default arguments returns an Array of paths and silently filters out ignored root directories, while passing namespaces: true returns a Hash of dir to Module and ignored: true includes ignored roots
- assert loader.eager_load with default force: false skips files configured with do_not_eager_load leaving their autoloads pending, whereas force: true forces them to load while still ignoring paths in loader.ignore
ファイル
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- src/loader_defaults.rb
- src/trees/custom_namespace/gateways/stripe.rb
- src/trees/custom_namespace/invoice.rb
- src/trees/default_root/gateways/stripe.rb
- src/trees/default_root/invoice.rb
- src/trees/eager_exclusions/eager_excluded.rb
- src/trees/eager_exclusions/eager_ignored.rb
- src/trees/eager_exclusions/eager_normal.rb
- src/trees/ignored_root/dummy.rb
- src/trees/mismatch_namespace/invoice.rb
- test/contract.rb
ソース
source "https://rubygems.org"
gem "zeitwerk", "2.8.3"
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
minitest (5.27.0)
zeitwerk (2.8.3)
PLATFORMS
ruby
x64-mingw-ucrt
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
# Zeitwerk Loader Defaults and Namespace Scoping
## Search Findings
`search_known_solution` returned three existing samples:
- `sha256:fe3c29ae9cd4ff1fa9203d040133804b1057836934a88d30aab4c109c86f7647`: Autoloading constants with Zeitwerk, acronym inflections, and `Zeitwerk::NameError` mechanics.
- `sha256:3aed1aec35956317dc802d4cbf7266ff5aa5230d8c32e41cade6cadb5f1fbb5f`: Managing the code reloading lifecycle and `ReloadingDisabledError`.
- `sha256:dd1e2e505fdc6901c86401bacecf74a2ddad8865c5724c15775e04ee6513ceea`: Constant path formatting in `on_load` callbacks.
This sample focuses on default argument handling in `Zeitwerk::Loader#push_dir`, `Zeitwerk::Loader#dirs`, and `Zeitwerk::Loader#eager_load`.
## Failure Mode
Fails loudly upon constant reference or during `eager_load` with `Zeitwerk::NameError` ("expected file ... to define constant Foo, but didn't") when classes are nested inside a directory-named namespace, or with `NameError: uninitialized constant` when referencing an un-autovivified root module.
## Key Behaviors
1. **`push_dir(path, namespace: Object)`**:
- The default value for `namespace:` is `Object`.
- Zeitwerk does not infer a namespace from the directory name or path. A file at `services/billing/invoice.rb` is expected to define top-level `::Invoice`, not `Billing::Invoice`.
- Wrapping the class definition inside `module Billing; class Invoice; ...` causes Zeitwerk's autoload on `Invoice` to raise `Zeitwerk::NameError`.
- Scoping under a custom namespace requires explicitly passing `namespace: Billing`. The namespace must be an existing, named `Module` or `Class`; strings, symbols, and anonymous modules raise `Zeitwerk::Error`.
2. **`dirs(namespaces: false, ignored: false)`**:
- Calling `loader.dirs` without arguments returns an `Array` of paths, not a `Hash`.
- By default (`ignored: false`), any root directory passed to `loader.ignore(...)` is excluded from the returned collection.
- Passing `namespaces: true` returns a `Hash` mapping root paths to their namespace modules (`{ dir => Object }`).
- Passing `ignored: true` includes ignored root directories.
3. **`eager_load(force: false)`**:
- Calling `loader.eager_load` defaults `force:` to `false`, respecting files and directories registered via `do_not_eager_load` and leaving their autoloads pending for on-demand loading.
- Passing `force: true` overrides `do_not_eager_load` exclusions while still honoring `loader.ignore`.
{"case":{"believed":"push_dir without an explicit namespace parameter scopes autoloaded constants under a module matching the directory name.","caseId":"case:sha256:26c3ade4ca853353ea2a84c683a31e617c52ef880a2f700ff2cd44d54fb01d9b","contract":["assert push_dir with namespace left unset defaults the root namespace to Object rather than inferring a namespace from the directory name, mapping the directory to Object in all_expected_cpaths and expecting unprefixed top-level constants","assert a file that defines its class nested inside a directory-named module raises Zeitwerk::NameError under default push_dir because Zeitwerk expects the unprefixed top-level constant name","assert scoping files under a custom parent module requires explicitly passing namespace: Module to push_dir, which expects prefixed constant paths and autovivifies subdirectories under that module","assert push_dir validates the namespace argument strictly, rejecting strings, symbols, and anonymous modules with Zeitwerk::Error","assert loader.dirs with default arguments returns an Array of paths and silently filters out ignored root directories, while passing namespaces: true returns a Hash of dir to Module and ignored: true includes ignored roots","assert loader.eager_load with default force: false skips files configured with do_not_eager_load leaving their autoloads pending, whereas force: true forces them to load while still ignoring paths in loader.ignore"],"goal":"Configure root directories with Zeitwerk and handle default top-level Object namespace and directory-filtering defaults in push_dir and dirs without name collisions or missing constant errors","kind":"HOW","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader#push_dir","Zeitwerk::Loader#dirs","Zeitwerk::Loader#eager_load","Zeitwerk::Loader#all_expected_cpaths","Zeitwerk::Loader#cpath_expected_at"]},"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#push_dir","Zeitwerk::Loader#dirs","Zeitwerk::Loader#eager_load","Zeitwerk::Loader#all_expected_cpaths","Zeitwerk::Loader#cpath_expected_at"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "zeitwerk"
module LoaderDefaults
TREES = File.expand_path("trees", __dir__)
def self.tree(name)
File.join(TREES, name)
end
def self.file(tree_name, *subpath)
File.join(tree(tree_name), *subpath)
end
def self.loader_for(tree_name, namespace: Object)
loader = Zeitwerk::Loader.new
loader.push_dir(tree(tree_name), namespace: namespace)
loader.setup
loader
end
end
# frozen_string_literal: true
module CustomBilling
module Gateways
class Stripe
PROVIDER = :custom_stripe
end
end
end
# frozen_string_literal: true
module CustomBilling
class Invoice
STATUS = :custom_ns_evaluated
end
end
# frozen_string_literal: true
module Gateways
class Stripe
PROVIDER = :stripe
end
end
# frozen_string_literal: true
class Invoice
STATUS = :default_root_evaluated
end
# frozen_string_literal: true
class EagerExcluded
STATUS = :excluded_loaded
end
# frozen_string_literal: true
class EagerIgnored
STATUS = :ignored_loaded
end
# frozen_string_literal: true
class EagerNormal
STATUS = :normal_loaded
end
# frozen_string_literal: true
class Dummy
STATUS = :ignored_dummy
end
# frozen_string_literal: true
# The author assumed push_dir('.../mismatch_namespace') namespaces under InferredBilling,
# but Zeitwerk defaults root namespace to Object and expects top-level Invoice.
module InferredBilling
class Invoice
STATUS = :mismatch
end
end
# frozen_string_literal: true
require "minitest/autorun"
require_relative "../src/loader_defaults"
# Explicit namespace module used in contract tests
module CustomBilling; end
class ZeitwerkDefaultsContract < Minitest::Test
def setup
@loaders = []
end
def teardown
@loaders.each do |loader|
loader.unload if loader.reloading_enabled? || loader.instance_variable_get(:@setup)
loader.unregister
end
# Clean up top-level constants created during tests
%i[Invoice Gateways Dummy EagerNormal EagerExcluded EagerIgnored InferredBilling].each do |cname|
Object.send(:remove_const, cname) if Object.const_defined?(cname, false)
end
# Clean up nested constants inside CustomBilling
%i[Invoice Gateways].each do |cname|
CustomBilling.send(:remove_const, cname) if CustomBilling.const_defined?(cname, false)
end
end
def track(loader)
@loaders << loader
loader
end
def test_push_dir_defaults_root_namespace_to_object_and_expects_unprefixed_constants
dir = LoaderDefaults.tree("default_root")
invoice_file = LoaderDefaults.file("default_root", "invoice.rb")
stripe_file = LoaderDefaults.file("default_root", "gateways", "stripe.rb")
gateways_dir = LoaderDefaults.file("default_root", "gateways")
loader = track(Zeitwerk::Loader.new)
# When namespace: is omitted, it defaults to Object (not a module matching the directory name)
loader.push_dir(dir)
# dirs with default options (namespaces: false, ignored: false) returns an Array[String]
assert_equal [dir], loader.dirs
assert_instance_of Array, loader.dirs
# dirs(namespaces: true) reveals the default root namespace is Object
assert_equal({ dir => Object }, loader.dirs(namespaces: true))
# Expected constant paths default to top-level unprefixed constants
assert_equal "Invoice", loader.cpath_expected_at(invoice_file)
assert_equal "Gateways::Stripe", loader.cpath_expected_at(stripe_file)
expected_map = {
dir => "Object",
invoice_file => "Invoice",
gateways_dir => "Gateways",
stripe_file => "Gateways::Stripe"
}
assert_equal expected_map, loader.all_expected_cpaths
loader.setup
# Autoloads resolve into top-level Object
assert_equal :default_root_evaluated, Invoice::STATUS
assert_equal :stripe, Gateways::Stripe::PROVIDER
end
def test_nested_namespace_in_file_raises_name_error_when_root_namespace_defaults_to_object
dir = LoaderDefaults.tree("mismatch_namespace")
invoice_file = LoaderDefaults.file("mismatch_namespace", "invoice.rb")
loader = track(Zeitwerk::Loader.new)
loader.push_dir(dir) # namespace defaults to Object
loader.setup
# Referencing Invoice triggers the autoload, but the file wrapped its definition in InferredBilling
err = assert_raises(Zeitwerk::NameError) { Invoice }
assert_equal "expected file #{invoice_file} to define constant Invoice, but didn't", err.message
assert_equal :Invoice, err.name
end
def test_explicit_namespace_scopes_all_constants_and_autovivifies_subdirectories
dir = LoaderDefaults.tree("custom_namespace")
invoice_file = LoaderDefaults.file("custom_namespace", "invoice.rb")
stripe_file = LoaderDefaults.file("custom_namespace", "gateways", "stripe.rb")
gateways_dir = LoaderDefaults.file("custom_namespace", "gateways")
loader = track(Zeitwerk::Loader.new)
# Explicitly scoping under CustomBilling root namespace
loader.push_dir(dir, namespace: CustomBilling)
assert_equal({ dir => CustomBilling }, loader.dirs(namespaces: true))
assert_equal "CustomBilling::Invoice", loader.cpath_expected_at(invoice_file)
assert_equal "CustomBilling::Gateways::Stripe", loader.cpath_expected_at(stripe_file)
expected_map = {
dir => "CustomBilling",
invoice_file => "CustomBilling::Invoice",
gateways_dir => "CustomBilling::Gateways",
stripe_file => "CustomBilling::Gateways::Stripe"
}
assert_equal expected_map, loader.all_expected_cpaths
loader.setup
# Constants are autoloaded under CustomBilling namespace
assert_equal :custom_ns_evaluated, CustomBilling::Invoice::STATUS
assert_equal :custom_stripe, CustomBilling::Gateways::Stripe::PROVIDER
# CustomBilling::Gateways is autovivified as a Module
assert_kind_of Module, CustomBilling::Gateways
refute_kind_of Class, CustomBilling::Gateways
end
def test_push_dir_validates_namespace_argument_strictly
dir = LoaderDefaults.tree("default_root")
loader = track(Zeitwerk::Loader.new)
# String is rejected
err_str = assert_raises(Zeitwerk::Error) { loader.push_dir(dir, namespace: "CustomBilling") }
assert_match(/is not a class or module object, should be/, err_str.message)
# Symbol is rejected
err_sym = assert_raises(Zeitwerk::Error) { loader.push_dir(dir, namespace: :CustomBilling) }
assert_match(/is not a class or module object, should be/, err_sym.message)
# Anonymous module is rejected
anon = Module.new
err_anon = assert_raises(Zeitwerk::Error) { loader.push_dir(dir, namespace: anon) }
assert_match(/root namespaces cannot be anonymous/, err_anon.message)
end
def test_dirs_defaults_to_filtering_ignored_roots_and_returning_array_of_paths
active_dir = LoaderDefaults.tree("default_root")
ignored_dir = LoaderDefaults.tree("ignored_root")
loader = track(Zeitwerk::Loader.new)
loader.push_dir(active_dir)
loader.push_dir(ignored_dir)
loader.ignore(ignored_dir)
# Default dirs call (namespaces: false, ignored: false) returns Array with ignored roots filtered out
assert_equal [active_dir], loader.dirs
assert_instance_of Array, loader.dirs
# ignored: true retains ignored root directories
assert_equal [active_dir, ignored_dir], loader.dirs(ignored: true)
# namespaces: true returns Hash[String, Module], still filtering ignored roots by default
assert_equal({ active_dir => Object }, loader.dirs(namespaces: true))
assert_equal({ active_dir => Object, ignored_dir => Object }, loader.dirs(namespaces: true, ignored: true))
end
def test_eager_load_defaults_to_respecting_exclusions_unless_force_is_true
dir = LoaderDefaults.tree("eager_exclusions")
normal_file = LoaderDefaults.file("eager_exclusions", "eager_normal.rb")
excluded_file = LoaderDefaults.file("eager_exclusions", "eager_excluded.rb")
ignored_file = LoaderDefaults.file("eager_exclusions", "eager_ignored.rb")
loader = track(Zeitwerk::Loader.new)
loader.push_dir(dir)
loader.do_not_eager_load(excluded_file)
loader.ignore(ignored_file)
loader.setup
# Default eager_load (force: false) loads normal files, skips excluded files
loader.eager_load
# Normal file was eager loaded (autoload consumed)
assert_nil Object.autoload?(:EagerNormal)
assert Object.const_defined?(:EagerNormal, false)
# Excluded file was NOT eager loaded; its autoload remains pending
assert_equal excluded_file, Object.autoload?(:EagerExcluded)
# On-demand autoload of excluded constant still works
assert_equal :excluded_loaded, EagerExcluded::STATUS
assert_nil Object.autoload?(:EagerExcluded)
# Ignored file was never registered for autoloading
assert_nil Object.autoload?(:EagerIgnored)
refute Object.const_defined?(:EagerIgnored, false)
end
end