Ejemplo
zeitwerk 2.8.3: Autovivify namespace modules with Zeitwerk across empty directories, non-Ruby assets, and multi-level subdirectory trees
Muestra verificada para gem zeitwerk 2.8.3: Autovivify namespace modules with Zeitwerk across empty directories, non-Ruby assets, and multi-level…
sha256:8fa0af5cf0e7a129c995c34fca5c50864a243c0f2ab9a568a2c7a3633e99b46b
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 2
- Claves de firma que lo compilaron
- 1
Entorno declarado
ruby linux x64 ruby ruby rubygems
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-16 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | SKIPPED | compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Autovivify namespace modules with Zeitwerk across empty directories, non-Ruby assets, and multi-level subdirectory trees
- Paquetes
- Símbolos
-
- Zeitwerk::Loader#push_dir
- Zeitwerk::Loader#setup
- Zeitwerk::Loader#all_expected_cpaths
- Zeitwerk::Loader#cpath_expected_at
- Zeitwerk::Loader#eager_load
- Entorno
- ruby
- Creado
- 2026-08-16T17:20:20Z
Contrato
- assert empty directories and directories containing only non-Ruby assets or hidden dotfiles do not autovivify namespace modules and raise NameError on constant access rather than resolving to Module instances
- assert loader.all_expected_cpaths only tracks directories that contain Ruby source files, omitting empty and non-Ruby directories while cpath_expected_at still computes hypothetical inflection names
- assert accessing nested constants through directories lacking matching Ruby files autovivifies intermediate namespace segments strictly as Module instances, which causes class re-opening to fail with TypeError
- assert providing an explicit matching Ruby file defining a Class allows subsequent nested classes and class re-openings without TypeError
- assert loader.eager_load walks all valid Ruby file trees and autovivifies intermediate modules while leaving empty and non-Ruby directories completely uninitialized
Archivos
- Gemfile
- NOTES.md
- app/asset_dir/README.md
- app/asset_dir/config.json
- app/backup_dir/handler.rb.bak
- app/billing.rb
- app/billing/invoice.rb
- app/billing/invoice/line_item.rb
- app/domain/order/item.rb
- app/empty_dir/.gitkeep
- app/hidden_dir/.secret.rb
- app/services/README.md
- app/services/worker.rb
- csx.json
- test/contract.rb
Código fuente
source "https://rubygems.org"
gem "zeitwerk", "2.8.3"
# Zeitwerk Directory Autovivification and Asset Handling
## Search Findings
`search_known_solution` returned existing samples covering:
- `sha256:fe3c29ae9cd4ff1fa9203d040133804b1057836934a88d30aab4c109c86f7647`: Autoloading constants with Zeitwerk, acronym inflections, and `Zeitwerk::NameError` mechanics.
- `sha256:3aed1aec35956317dc802d4cbf7266ff5aa5230d8c32e41cade6cadb5f1fbb5f`: Managing code reloading before setup and reload lifecycle errors.
- `sha256:75407f503d18673b17265d62c127a0e8fb4349c235b2832a4d25826f1d56f9fa`: Releasing managed directories and retained memory via unload and unregister.
- `sha256:f5e879ad7fff251e4014b28be48663de7b4514a83f5c057a70ea7fb6c2917dd6`: Collapsing directories without flattening nested subdirectory namespaces.
- `sha256:d31e33032473c664fa7a0c4dcd36a16f9cf0d615144d0f7d58faaa8bcd993b71`: Loader root defaults and top-level `Object` namespace scoping.
This sample focuses on the boundary behavior of Zeitwerk when encountering empty subdirectories, non-Ruby assets, hidden files, and missing parent `.rb` files during namespace autovivification.
## Failure Mode
Fails loudly with `NameError: uninitialized constant` when accessing empty or non-Ruby directories, and with `TypeError: ... is not a class` when attempting to open an autovivified module as a class.
## Key Behaviors
1. **Empty and Non-Ruby Directories**:
- Zeitwerk scans directories specifically for `.rb` files.
- If a directory is empty (`app/empty_dir`), contains only static assets (`app/asset_dir/README.md`, `config.json`), hidden files (`app/hidden_dir/.secret.rb`), or non-matching extensions (`app/backup_dir/handler.rb.bak`), Zeitwerk treats the directory as absent from the constant graph.
- The constant is not autovivified, is not in `loader.all_expected_cpaths`, and referencing it raises `NameError: uninitialized constant`.
- `loader.cpath_expected_at` computes the hypothetical constant name according to inflection rules, but no autoload is registered without backing `.rb` files.
2. **Autovivified Modules vs Class Definitions**:
- When a subdirectory contains a Ruby file (e.g. `app/domain/order/item.rb`) but has no matching parent files (`app/domain.rb` or `app/domain/order.rb`), Zeitwerk autovivifies intermediate namespace segments (`Domain`, `Domain::Order`) as `Module` instances upon access.
- Because Ruby prohibits reopening an existing `Module` as a `Class`, running `class Domain::Order` subsequently raises `TypeError: Order is not a class`.
- To make an intermediate namespace a class, an explicit matching file (e.g. `app/billing/invoice.rb`) must define `class Billing::Invoice` before child namespaces (`app/billing/invoice/line_item.rb`) are resolved.
3. **Eager Loading**:
- `loader.eager_load` traverses and loads all valid Ruby source files and autovivifies intermediate namespaces, while leaving non-Ruby and empty directories untouched and uninitialized.
# Asset Directory Documentation
This directory contains non-Ruby static assets and configuration files.
{
"setting": "enabled",
"threshold": 100
}
# frozen_string_literal: true
module BackupDir
class Handler
def run
:backup
end
end
end
# frozen_string_literal: true
module Billing
end
# frozen_string_literal: true
class Billing::Invoice
attr_reader :number
def initialize(number = "INV-001")
@number = number
end
end
# frozen_string_literal: true
class Billing::Invoice
class LineItem
attr_reader :description, :amount
def initialize(description = "Service fee", amount = 50)
@description = description
@amount = amount
end
end
end
# frozen_string_literal: true
module Domain
module Order
class Item
attr_reader :price
def initialize(price = 100)
@price = price
end
end
end
end
# Marker for empty directory
# frozen_string_literal: true
module HiddenDir
SECRET = "hidden-token-value"
end
# Services Documentation
This directory contains backend service workers alongside Markdown notes.
# frozen_string_literal: true
module Services
class Worker
def perform
:done
end
end
end
{"case":{"believed":"Zeitwerk autovivifies a namespace module for every subdirectory in a managed root directory, treating empty folders and non-Ruby asset directories as constant namespaces.","caseId":"case:sha256:f2b2c13617569b8b8a13d156ecc4f7c5e7be756ebbe3fd8c911b6bf65ee439a5","contract":["assert empty directories and directories containing only non-Ruby assets or hidden dotfiles do not autovivify namespace modules and raise NameError on constant access rather than resolving to Module instances","assert loader.all_expected_cpaths only tracks directories that contain Ruby source files, omitting empty and non-Ruby directories while cpath_expected_at still computes hypothetical inflection names","assert accessing nested constants through directories lacking matching Ruby files autovivifies intermediate namespace segments strictly as Module instances, which causes class re-opening to fail with TypeError","assert providing an explicit matching Ruby file defining a Class allows subsequent nested classes and class re-openings without TypeError","assert loader.eager_load walks all valid Ruby file trees and autovivifies intermediate modules while leaving empty and non-Ruby directories completely uninitialized"],"goal":"Autovivify namespace modules with Zeitwerk across empty directories, non-Ruby assets, and multi-level subdirectory trees","kind":"HOW","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader#push_dir","Zeitwerk::Loader#setup","Zeitwerk::Loader#all_expected_cpaths","Zeitwerk::Loader#cpath_expected_at","Zeitwerk::Loader#eager_load"]},"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#setup","Zeitwerk::Loader#all_expected_cpaths","Zeitwerk::Loader#cpath_expected_at","Zeitwerk::Loader#eager_load"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "zeitwerk"
app_dir = File.expand_path("../app", __dir__)
loader = Zeitwerk::Loader.new
loader.push_dir(app_dir)
loader.setup
# 1. Empty directories and non-Ruby asset directories do not autovivify modules
[:EmptyDir, :AssetDir, :HiddenDir, :BackupDir].each do |const_name|
if Object.const_defined?(const_name)
raise "Expected #{const_name} not to be defined on Object, but it was"
end
begin
Object.const_get(const_name)
raise "Expected accessing #{const_name} to raise NameError, but it resolved"
rescue NameError
# Expected: uninitialized constant
end
end
# 2. all_expected_cpaths only tracks directories with Ruby source files
cpaths = loader.all_expected_cpaths.values
["EmptyDir", "AssetDir", "HiddenDir", "BackupDir"].each do |omitted|
if cpaths.include?(omitted)
raise "Expected all_expected_cpaths not to contain #{omitted}, but got: #{cpaths.inspect}"
end
end
expected_cpaths = [
"Services",
"Services::Worker",
"Domain",
"Domain::Order",
"Domain::Order::Item",
"Billing",
"Billing::Invoice",
"Billing::Invoice::LineItem"
]
expected_cpaths.each do |cpath|
unless cpaths.include?(cpath)
raise "Expected all_expected_cpaths to include #{cpath}, but got: #{cpaths.inspect}"
end
end
asset_dir_path = File.join(app_dir, "asset_dir")
unless loader.cpath_expected_at(asset_dir_path) == "AssetDir"
raise "Expected cpath_expected_at for asset_dir to return 'AssetDir'"
end
# 3. Directories without matching .rb files autovivify intermediate segments strictly as Module instances
unless Services.instance_of?(Module)
raise "Expected Services to autovivify as Module, got #{Services.class}"
end
worker = Services::Worker.new
unless worker.perform == :done
raise "Expected Services::Worker#perform to return :done, got #{worker.perform.inspect}"
end
unless Domain.instance_of?(Module)
raise "Expected Domain to autovivify as Module, got #{Domain.class}"
end
unless Domain::Order.instance_of?(Module)
raise "Expected Domain::Order to autovivify as Module, got #{Domain::Order.class}"
end
item = Domain::Order::Item.new
unless item.price == 100
raise "Expected Domain::Order::Item#price to return 100, got #{item.price}"
end
type_error_raised = false
begin
class Domain::Order
end
rescue TypeError
type_error_raised = true
end
unless type_error_raised
raise "Expected reopening autovivified module Domain::Order as a class to raise TypeError"
end
# 4. Explicit matching Ruby file allows Class definition and class re-opening
unless Billing::Invoice.instance_of?(Class)
raise "Expected Billing::Invoice to be a Class, got #{Billing::Invoice.class}"
end
class Billing::Invoice
def status
:paid
end
end
invoice = Billing::Invoice.new
unless invoice.status == :paid
raise "Expected reopened Billing::Invoice#status to return :paid"
end
line_item = Billing::Invoice::LineItem.new
unless line_item.amount == 50
raise "Expected Billing::Invoice::LineItem#amount to return 50"
end
# 5. Eager load walks valid Ruby trees and keeps empty/asset directories uninitialized
loader.eager_load
[:EmptyDir, :AssetDir, :HiddenDir, :BackupDir].each do |const_name|
if Object.const_defined?(const_name)
raise "Expected #{const_name} to remain undefined after eager_load, but it was defined"
end
end
loader.unregister
puts "Contract passed: all Zeitwerk autovivification and asset handling assertions verified."