pax_global_header 0000666 0000000 0000000 00000000064 14422670021 0014510 g ustar 00root root 0000000 0000000 52 comment=c3c0ecbd1b7fdbd11e26aac85630ac5b42aeb337
zeitwerk-2.6.8/ 0000775 0000000 0000000 00000000000 14422670021 0013371 5 ustar 00root root 0000000 0000000 zeitwerk-2.6.8/.github/ 0000775 0000000 0000000 00000000000 14422670021 0014731 5 ustar 00root root 0000000 0000000 zeitwerk-2.6.8/.github/workflows/ 0000775 0000000 0000000 00000000000 14422670021 0016766 5 ustar 00root root 0000000 0000000 zeitwerk-2.6.8/.github/workflows/ci.yml 0000664 0000000 0000000 00000001151 14422670021 0020102 0 ustar 00root root 0000000 0000000 name: "CI"
on:
push:
pull_request:
branches:
- "main"
jobs:
test:
strategy:
fail-fast: false
matrix:
os:
- "ubuntu-latest"
- "macos-latest"
- "windows-latest"
ruby-version:
- "2.5"
- "2.6"
- "2.7"
- "3.0"
- "3.1"
- "3.2"
- "head"
runs-on: ${{ matrix.os }}
steps:
- uses: "actions/checkout@v3"
- uses: "ruby/setup-ruby@v1"
with:
ruby-version: ${{ matrix.ruby-version }}
bundler-cache: true
- run: "bundle exec rake"
zeitwerk-2.6.8/.github/workflows/keep-an-eye-on-ruby-head.yml 0000664 0000000 0000000 00000001030 14422670021 0024073 0 ustar 00root root 0000000 0000000 name: "Keep an eye on Ruby HEAD"
on:
workflow_dispatch:
schedule:
- cron: "11 9 * * *"
jobs:
test:
strategy:
fail-fast: false
matrix:
os:
- "ubuntu-latest"
- "macos-latest"
- "windows-latest"
ruby-version:
- "head"
runs-on: ${{ matrix.os }}
steps:
- uses: "actions/checkout@v3"
- uses: "ruby/setup-ruby@v1"
with:
ruby-version: ${{ matrix.ruby-version }}
bundler-cache: true
- run: "bundle exec rake"
zeitwerk-2.6.8/.gitignore 0000664 0000000 0000000 00000000034 14422670021 0015356 0 ustar 00root root 0000000 0000000 Gemfile.lock
test/tmp
*.gem
zeitwerk-2.6.8/CHANGELOG.md 0000664 0000000 0000000 00000050376 14422670021 0015215 0 ustar 00root root 0000000 0000000 # CHANGELOG
## 2.6.8 (28 April 2023)
* The new `Zeitwerk::Loader.for_gem_extension` gives you a loader configured
according to the conventions of a [gem
extension](https://guides.rubygems.org/name-your-gem/).
Please check its
[documentation](https://github.com/fxn/zeitwerk#for_gem_extension) for further
details.
## 2.6.7 (10 February 2023)
* Reset module state on `Zeitwerk::NameError`.
If an autoload is triggered, the file is loaded successfully, but the expected
constant does not get defined, Ruby resets the state of the module. In
particular, `autoload?` returns `nil` for that constant name, and `constants`
does not include the constant name (starting with Ruby 3.1).
Zeitwerk is more strict, not defining the expected constant is an error
condition and the loader raises `Zeitwerk::NameError`. But this happens during
the `require` call and the exception prevents Ruby from doing that cleanup.
With this change, the parent module is left in a state that makes more sense
and is consistent with what Ruby does.
* A message is logged if an autoload did not define the expected constant.
When that happens, `Zeitwerk::NameError` is raised and you normally see the
exception. But if the error is shallowed, and you are inspecting the logs to
investigate something, this new message may be helpful.
* By default, `Zeitwerk::Loader#dirs` filters ignored root directories out.
Please, pass `ignored: true` if you want them included.
It is very strange to configure a root directory and also ignore it, the edge
case is supported only for completeness. However, in that case, client code
listing root directories rarely needs the ignored ones.
* Documentation improvements.
* Enforcement of private interfaces continues with another gradual patch.
## 2.6.6 (8 November 2022)
* The new `eager_load_namespace` had a bug when eager loading certain namespaces
with collapsed directories. This has been fixed.
## 2.6.5 (6 November 2022)
* Controlled errors in a couple of situations:
- Attempting to eager load or reload without previously invoking `setup` now
raises `Zeitwerk::SetupRequired`.
- The method `Zeitwerk::Loader#push_dir` raises `Zeitwerk::Error` if it gets
an anonymous custom namespace.
These should be backwards compatible, because they raise in circumstances that
didn't work anyway. The goal here is to provide a meaningful error upfront.
* Enforcement of private interfaces continues with another gradual patch.
## 2.6.4 (1 November 2022)
Ruby does not have gem-level visibility, so sometimes you need things to be
`public` for them to be accessible internally. But they do not belong to the
public interface of the gem.
A method that is undocumented and marked as `@private` in the source code is
clearly private API, regardless of its formal Ruby visibility.
This release starts a series of gradual patches in which private interface is
enforced with stricter formal visibility.
## 2.6.3 (31 October 2022)
* `v2.6.2` introduced a regression in the logic that checks whether two loaders
want to manage the same root directories. It has been fixed.
## 2.6.2 (31 October 2022)
* `Zeitwerk::Loader#load_file` allows you to load an individual Ruby file. Check
its [documentation](https://github.com/fxn/zeitwerk#loading-individual-files)
for details.
* `Zeitwerk::Loader#eager_load_dir` allows you to eager load a directory,
recursively. Check its
[documentation](https://github.com/fxn/zeitwerk#eager-load-directories) for
details.
* `Zeitwerk::Loader#eager_load_namespace` allows you to eager a namespace,
recursively. Namespaces are global, this method loads only what the receiver
manages from that namespace, if anything. Check its
[documentation](https://github.com/fxn/zeitwerk#eager-load-namespaces) for
details.
* `Zeitwerk::Loader.eager_load_namespace` broadcasts `eager_load_namespace` to
all registered loaders. Check its
[documentation](https://github.com/fxn/zeitwerk#eager-load-namespaces-shared-by-several-loaders)
for details.
* Documents [shadowed files](https://github.com/fxn/zeitwerk#shadowed-files).
They always existed, but were not covered by the documentation.
* Other assorted documentation improvements.
## 2.6.1 (1 October 2022)
* `Zeitwerk::Loader#dirs` allows you to instrospect the root directories
configured in the receiver. Please check its
[documentation](https://github.com/fxn/zeitwerk#introspection) for details.
## 2.6.0 (13 June 2022)
* Directories are processed in lexicographic order.
Different file systems may list directories in different order, and with this
change we ensure that client code eager loads consistently across platforms,
for example.
* Before this release, subdirectories of root directories always represented
namespaces (unless ignored or collapsed). From now on, to be considered
namespaces they also have to contain at least one non-ignored Ruby file with
extension `.rb`, directly or recursively.
If you know beforehand a certain directory or directory pattern does not
represent a namespace, it is intentional and more efficient to tell Zeitwerk
to [ignore](https://github.com/fxn/zeitwerk#ignoring-parts-of-the-project) it.
However, if you don't do so and have a directory `tasks` that only contains
Rake files, arguably that directory is not meant to represent a Ruby module.
Before, Zeitwerk would define a top-level `Tasks` module after it; now, it
does not.
This feature is also handy for projects that have directories with auxiliary
resources mixed in the project tree in a way that is too dynamic for an ignore
pattern to be practical. See https://github.com/fxn/zeitwerk/issues/216.
In the unlikely case that an existing project has an empty directory for the
sole purpose of defining a totally empty module (no code, and no nested
classes or modules), such module has now to be defined in a file.
Directories are scanned again on reloads.
* On setup, loaders created with `Zeitwerk::Loader.for_gem` issue warnings if
`lib` has extra, non-ignored Ruby files or directories.
This is motivated by existing gems with directories under `lib` that are not
meant to define Ruby modules, like directories for Rails generators, for
instance.
This warning can be silenced in the unlikely case that the extra stuff is
actually autoloadable and has to be managed by Zeitwerk.
Please, check the [documentation](https://github.com/fxn/zeitwerk#for_gem) for
further details.
This method returns an instance of a private subclass of `Zeitwerk::Loader`
now, but you cannot rely on the type, just on the interface.
## 2.5.4 (28 January 2022)
* If a file did not define the expected constant, there was a reload, and there were `on_unload` callbacks, Zeitwerk still tried to access the constant during reload, which raised. This has been corrected.
## 2.5.3 (30 December 2021)
* The change introduced in 2.5.2 implied a performance regression that was particularly dramatic in Ruby 3.1. We'll address [#198](https://github.com/fxn/zeitwerk/issues/198) in a different way.
## 2.5.2 (27 December 2021)
* When `Module#autoload` triggers the autovivification of an implicit namespace, `$LOADED_FEATURES` now gets the correspoding directory pushed. This is just a tweak to Zeitwerk's `Kernel#require` decoration. That way it acts more like the original, and cooperates better with other potential `Kernel#require` wrappers, like Bootsnap's.
## 2.5.1 (20 October 2021)
* Restores support for namespaces that are not hashable. For example namespaces that override the `hash` method with a different arity as shown in [#188](https://github.com/fxn/zeitwerk/issues/188).
## 2.5.0 (20 October 2021)
### Breaking changes
* Requires Ruby 2.5.
* Deletes the long time deprecated preload API. Instead of:
```ruby
loader.preload("app/models/user.rb")
```
just reference the constant on setup:
```ruby
loader.on_setup { User }
```
If you want to eager load a namespace, use the constants API:
```ruby
loader.on_setup do
Admin.constants(false).each { |cname| Admin.const_get(cname) }
end
```
### Bug fixes
* Fixes a bug in which a certain valid combination of overlapping trees managed by different loaders and ignored directories was mistakenly reported as having conflicting directories.
* Detects external namespaces defined with `Module#autoload`. If your project reopens a 3rd party namespace, Zeitwerk already detected it and did not consider the namespace to be managed by the loader (automatically descends, ignored for reloads, etc.). However, the loader did not do that if the namespace had only an autoload in the 3rd party code yet to be executed. Now it does.
### Callbacks
* Implements `Zeitwerk::Loader#on_setup`, which allows you to configure blocks of code to be executed on setup and on each reload. When the callback is fired, the loader is ready, you can refer to project constants in the block.
See the [documentation](https://github.com/fxn/zeitwerk#the-on_setup-callback) for further details.
* There is a new catch-all `Zeitwerk::Loader#on_load` that takes no argument and is triggered for all loaded objects:
```ruby
loader.on_load do |cpath, value, abspath|
# ...
end
```
Please, remember that if you want to trace the activity of a loader, `Zeitwerk::Loader#log!` logs plenty of information.
See the [documentation](https://github.com/fxn/zeitwerk#the-on_load-callback) for further details.
* The block of the existing `Zeitwerk::Loader#on_load` receives also the value stored in the constant, and the absolute path to its corresponding file or directory:
```ruby
loader.on_load("Service::NotificationsGateway") do |klass, abspath|
# ...
end
```
Remember that blocks can be defined to take less arguments than passed. So this change is backwards compatible. If you had
```ruby
loader.on_load("Service::NotificationsGateway") do
Service::NotificationsGateway.endpoint = ...
end
```
That works.
* Implements `Zeitwerk::Loader#on_unload`, which allows you to configure blocks of code to be executed before a certain class or module gets unloaded:
```ruby
loader.on_unload("Country") do |klass, _abspath|
klass.clear_cache
end
```
These callbacks are invoked during unloading, which happens in an unspecified order. Therefore, they should not refer to reloadable constants.
You can also be called for all unloaded objects:
```ruby
loader.on_unload do |cpath, value, abspath|
# ...
end
```
Please, remember that if you want to trace the activity of a loader, `Zeitwerk::Loader#log!` logs plenty of information.
See the [documentation](https://github.com/fxn/zeitwerk/blob/master/README.md#the-on_unload-callback) for further details.
### Assorted
* Performance improvements.
* Documentation improvements.
* The method `Zeitwerk::Loader#eager_load` accepts a `force` flag:
```ruby
loader.eager_load(force: true)
```
If passed, eager load exclusions configured with `do_not_eager_load` are not honoured (but ignored files and directories are).
This may be handy for test suites that eager load in order to ensure all files define the expected constant.
* Eliminates internal use of `File.realpath`. One visible consequence is that in logs root dirs are shown as configured if they contain symlinks.
* When an autoloaded file does not define the expected constant, Ruby clears state differently starting with Ruby 3.1. Unloading has been revised to be compatible with both behaviours.
* Logging prints a few new traces.
## 2.4.2 (27 November 2020)
* Implements `Zeitwerk::Loader#on_load`, which allows you to configure blocks of code to be executed after a certain class or module have been loaded:
```ruby
# config/environments/development.rb
loader.on_load("SomeApiClient") do
SomeApiClient.endpoint = "https://api.dev"
# config/environments/production.rb
loader.on_load("SomeApiClient") do
SomeApiClient.endpoint = "https://api.prod"
end
```
See the [documentation](https://github.com/fxn/zeitwerk/blob/master/README.md#the-on_load-callback) for further details.
## 2.4.1 (29 October 2020)
* Use `__send__` instead of `send` internally.
## 2.4.0 (15 July 2020)
* `Zeitwerk::Loader#push_dir` supports an optional `namespace` keyword argument. Pass a class or module object if you want the given root directory to be associated with it instead of `Object`. Said class or module object cannot be reloadable.
* The default inflector is even more performant.
## 2.3.1 (29 June 2020)
* Saves some unnecessary allocations made internally by MRI. See [#125](https://github.com/fxn/zeitwerk/pull/125), by [@casperisfine](https://github.com/casperisfine).
* Documentation improvements.
* Internal code base maintenance.
## 2.3.0 (3 March 2020)
* Adds support for collapsing directories.
For example, if `booking/actions/create.rb` is meant to define `Booking::Create` because the subdirectory `actions` is there only for organizational purposes, you can tell Zeitwerk with `collapse`:
```ruby
loader.collapse("booking/actions")
```
The method also accepts glob patterns to support standardized project structures:
```ruby
loader.collapse("*/actions")
```
Please check the documentation for more details.
* Eager loading is idempotent, but now you can eager load again after reloading.
## 2.2.2 (29 November 2019)
* `Zeitwerk::NameError#name` has the name of the missing constant now.
## 2.2.1 (1 November 2019)
* Zeitwerk raised `NameError` when a managed file did not define its expected constant. Now, it raises `Zeitwerk::NameError` instead, so it is possible for client code to distinguish that mismatch from a regular `NameError`.
Regarding backwards compatibility, `Zeitwerk::NameError` is a subclass of `NameError`.
## 2.2.0 (9 October 2019)
* The default inflectors have API to override how to camelize selected basenames:
```ruby
loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
```
This addresses a common pattern, which is to use the basic inflectors with a few straightforward exceptions typically configured in a hash table or `case` expression. You no longer have to define a custom inflector if that is all you need.
* Documentation improvements.
## 2.1.10 (6 September 2019)
* Raises `Zeitwerk::NameError` with a better error message when a managed file or directory has a name that yields an invalid constant name when inflected. `Zeitwerk::NameError` is a subclass of `NameError`.
## 2.1.9 (16 July 2019)
* Preloading is soft-deprecated. The use case it was thought for is no longer. Please, if you have a legit use case for it, drop me a line.
* Root directory conflict detection among loaders takes ignored directories into account.
* Supports classes and modules with overridden `name` methods.
* Documentation improvements.
## 2.1.8 (29 June 2019)
* Fixes eager loading nested root directories. The new approach in 2.1.7 introduced a regression.
## 2.1.7 (29 June 2019)
* Prevent the inflector from deleting parts un multiword constants whose capitalization is the same. For example, `point_2d` should be inflected as `Point2d`, rather than `Point`. While the inflector is frozen, this seems to be just wrong, and the refinement should be backwards compatible, since those constants were not usable.
* Make eager loading consistent with auto loading with regard to detecting namespaces that do not define the matching constant.
* Documentation improvements.
## 2.1.6 (30 April 2019)
* Fixed: If an eager load exclusion contained an autoload for a namespace also
present in other branches that had to be eager loaded, they could be skipped.
* `loader.log!` is a convenient shortcut to get traces to `$stdout`.
* Allocates less strings.
## 2.1.5 (24 April 2019)
* Failed autoloads raise `NameError` as always, but with a more user-friendly
message instead of the original generic one from Ruby.
* Eager loading uses `const_get` now rather than `require`. A file that does not
define the expected constant could be eager loaded, but not autoloaded, which would be inconsistent. Thanks to @casperisfine for reporting this one and help testing the alternative.
## 2.1.4 (23 April 2019)
* Supports deletion of root directories in disk after they've been configured.
`push_dir` requires root directories to exist to prevent misconfigurations,
but after that Zeitwerk no longer assumes they exist. This might be convenient
if you removed one in a web application while a server was running.
## 2.1.3 (22 April 2019)
* Documentation improvements.
* Internal work.
## 2.1.2 (11 April 2019)
* Calling `reload` with reloading disabled raises `Zeitwerk::ReloadingDisabledError`.
## 2.1.1 (10 April 2019)
* Internal performance work.
## 2.1.0 (9 April 2019)
* `loaded_cpaths` is gone, you can ask if a constant path is going to be unloaded instead with `loader.to_unload?(cpath)`. Thanks to this refinement, Zeitwerk is able to consume even less memory. (Change included in a minor upgrade because the introspection API is not documented, and it still isn't, needs some time to settle down).
## 2.0.0 (7 April 2019)
* Reloading is disabled by default. In order to be able to reload you need to opt-in by calling `loader.enable_reloading` before setup. The motivation for this breaking change is twofold. On one hand, this is a design decision at the interface/usage level that reflects that the majority of use cases for Zeitwerk do not need reloading. On the other hand, if reloading is not enabled, Zeitwerk is able to use less memory. Notably, this is more optimal for large web applications in production.
## 1.4.3 (26 March 2019)
* Faster reload. If you're using `bootsnap`, requires at least version 1.4.2.
## 1.4.2 (23 March 2019)
* Includes an optimization.
## 1.4.1 (23 March 2019)
* Fixes concurrent autovivifications.
## 1.4.0 (19 March 2019)
* Trace point optimization for singleton classes by @casperisfine. See the use case, explanation, and patch in [#24](https://github.com/fxn/zeitwerk/pull/24).
* `Zeitwerk::Loader#do_not_eager_load` provides a way to have autoloadable files and directories that should be skipped when eager loading.
## 1.3.4 (14 March 2019)
* Files shadowed by previous occurrences defining the same constant path were being correctly skipped when autoloading, but not when eager loading. This has been fixed. This mimicks what happens when there are two files in `$LOAD_PATH` with the same relative name, only the first one is loaded by `require`.
## 1.3.3 (12 March 2019)
* Bug fix by @casperisfine: If the superclass or one of the ancestors of an explicit namespace `N` has an autoload set for constant `C`, and `n/c.rb` exists, the autoload for `N::C` proper could be missed.
## 1.3.2 (6 March 2019)
* Improved documentation.
* Zeitwerk creates at most one trace point per process, instead of one per loader. This is more performant when there are multiple gems managed by Zeitwerk.
## 1.3.1 (23 February 2019)
* After module vivification, the tracer could trigger one unnecessary autoload walk.
## 1.3.0 (21 February 2019)
* In addition to callables, loggers can now also be any object that responds to `debug`, which accepts one string argument.
## 1.2.0 (14 February 2019)
* Use `pretty_print` in the exception message for conflicting directories.
## 1.2.0.beta (14 February 2019)
* Two different loaders cannot be managing the same files. Now, `Zeitwerk::Loader#push_dir` raises `Zeitwerk::ConflictingDirectory` if it detects a conflict.
## 1.1.0 (14 February 2019)
* New class attribute `Zeitwerk::Loader.default_logger`, inherited by newly instantiated loaders. Default is `nil`.
* Traces include the loader tag in the prefix to easily distinguish them.
* Loaders now have a tag.
## 1.0.0 (12 February 2019)
* Documentation improvements.
## 1.0.0.beta3 (4 February 2019)
* Documentation improvements.
* `Zeitwerk::Loader#ignore` accepts glob patterns.
* New read-only introspection method `Zeitwerk::Loader.all_dirs`.
* New read-only introspection method `Zeitwerk::Loader#dirs`.
* New introspection predicate `Zeitwerk::Loader#loaded?(cpath)`.
## 1.0.0.beta2 (22 January 2019)
* `do_not_eager_load` has been removed, please use `ignore` to opt-out.
* Documentation improvements.
* Pronunciation section in the README, linking to sample audio file.
* All logged messages have a "Zeitwerk:" prefix for easy grepping.
* On reload, the logger also traces constants and autoloads removed.
## 1.0.0.beta (18 January 2019)
* Initial beta release.
zeitwerk-2.6.8/Gemfile 0000664 0000000 0000000 00000000264 14422670021 0014666 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source 'https://rubygems.org'
gemspec
gem "rake"
gem "minitest"
gem "minitest-focus"
gem "minitest-proveit"
gem "minitest-reporters"
gem "warning"
zeitwerk-2.6.8/MIT-LICENSE 0000664 0000000 0000000 00000002045 14422670021 0015026 0 ustar 00root root 0000000 0000000 Copyright (c) 2019–ω Xavier Noria
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zeitwerk-2.6.8/PROJECT_RULES.md 0000664 0000000 0000000 00000010272 14422670021 0015775 0 ustar 00root root 0000000 0000000 # Project rules
## Notation
It is very important that all the source code uses systematically the following naming conventions.
### Variables for constants
* `cname`: A constant name, for example `:User`. Must be a symbol.
* `cpath`: A constant path, for example `"User"` or `"Hotel::Pricing"`. Must be a string.
* `cref`: A constant reference represented as an array of two elements. The first one a class or module object, and the second one a constant name as a symbol. For example `[Admin, :UsersController]`.
### Variables for paths
You should always pick the most specific option:
* `file`: Absolute path of a file.
* `dir`: Absolute path of a directory.
* `abspath`: Absolute path of a file or directory.
Note that Zeitwerk does not deal with file or directory objects, only with paths. For brevity, we exploit this fact to adopt the convention `file`&`dir` instead of `filename`&`dirname` or somesuch.
## Paths
* The only relative file names allowed in the project come from users. For example, public methods like `push_dir` should understand relative paths.
* As soon as a relative file name comes from outside, it has to be converted to an absolute file name right away.
* Internally, you have to use exclusively absolute file names. In particular, any `autoload` or `require` calls have to be issued using absolute paths to avoid `$LOAD_PATH` walks.
* It is forbidden to do any sort of directory lookups when resolving relative file names.
* The only directory walks allowed are the ones needed to set autoloads. One pass, and as lazy as possible (do not descend into subdirectories until necessary).
* File and directory names should be kept as entered as much as possible so that APIs return them as they were, and logging matches too. This is specially relevant if there are symlinks involved.
## Class and module names
* Classes and modules may override the `name` method, therefore we cannot assume it returns their original constant path. Always use the helper `real_mod_name` on classes and modules coming from the user.
## Types
* All methods should have a documented signature using [RBS syntax](https://github.com/ruby/rbs/blob/master/docs/syntax.md).
* Use the most concise type always. Use a set when a set is the best choice, use `Module` when a class or module object is the natural data type (rather than its name).
* Use always symbols for constant names.
* Use always strings for constant paths.
* Use always strings for paths, not pathnames. Pathnames are only accepted coming from the user, but internally everything is strings.
## Public interface definition
Documented public methods conform the public interface. In particular:
* Public methods tagged as `@private` do not belong to the public interface.
* Undocumented public methods do not belong to the public interface. They are probably exploratory and may change or be deleted without warning. These are private interface in practice.
* Undocumented public methods can be used in the Rails integration. We control both repositories, and Rails usage may help refine the actual public interface.
Any release can change the private interface, including patch releases.
## Documentation
Try to word the documentation in terms of classes, modules, and namespaces. Do that with extra care to avoid introducing leaky metaphors.
We sacrifice there a bit of precision in order to communicate better. Some Ruby programmers do not have a deep understanding of constants, so better avoid being pedantic for didactic purposes. Those in the know understand what the documentation really says.
## Performance
Zeitwerk is infrastructure, so it should have minimal cost both in speed and memory usage.
Be extra careful, allocate as little as possible, store as little as possible. Always use absolute file names for `autoload` and `require`.
Always log using this pattern:
```ruby
log(message) if logger
```
to avoid unnecessary calls, and unnecessary computed values in the message.
Some projects may have hundreds of root directories and hundreds of thousands of files, please remember that.
However, do not write ugly code. Ugly code should be extremely justified in terms of performance. Instead, keep it simple, write simple performant code that reads well and is idiomatic.
zeitwerk-2.6.8/README.md 0000664 0000000 0000000 00000156352 14422670021 0014664 0 ustar 00root root 0000000 0000000 # Zeitwerk
[](https://rubygems.org/gems/zeitwerk)
[](https://github.com/fxn/zeitwerk/actions/workflows/ci.yml?query=branch%3main)
- [Introduction](#introduction)
- [Synopsis](#synopsis)
- [File structure](#file-structure)
- [The idea: File paths match constant paths](#the-idea-file-paths-match-constant-paths)
- [Inner simple constants](#inner-simple-constants)
- [Root directories and root namespaces](#root-directories-and-root-namespaces)
- [The default root namespace is `Object`](#the-default-root-namespace-is-object)
- [Custom root namespaces](#custom-root-namespaces)
- [Nested root directories](#nested-root-directories)
- [Implicit namespaces](#implicit-namespaces)
- [Explicit namespaces](#explicit-namespaces)
- [Collapsing directories](#collapsing-directories)
- [Testing compliance](#testing-compliance)
- [Usage](#usage)
- [Setup](#setup)
- [Generic](#generic)
- [for_gem](#for_gem)
- [for_gem_extension](#for_gem_extension)
- [Autoloading](#autoloading)
- [Eager loading](#eager-loading)
- [Eager load exclusions](#eager-load-exclusions)
- [Eager load directories](#eager-load-directories)
- [Eager load namespaces](#eager-load-namespaces)
- [Eager load namespaces shared by several loaders](#eager-load-namespaces-shared-by-several-loaders)
- [Global eager load](#global-eager-load)
- [Loading individual files](#loading-individual-files)
- [Reloading](#reloading)
- [Configuration and usage](#configuration-and-usage)
- [Thread-safety](#thread-safety)
- [Inflection](#inflection)
- [Zeitwerk::Inflector](#zeitwerkinflector)
- [Zeitwerk::GemInflector](#zeitwerkgeminflector)
- [Custom inflector](#custom-inflector)
- [Callbacks](#callbacks)
- [The on_setup callback](#the-on_setup-callback)
- [The on_load callback](#the-on_load-callback)
- [The on_unload callback](#the-on_unload-callback)
- [Technical details](#technical-details)
- [Logging](#logging)
- [Loader tag](#loader-tag)
- [Ignoring parts of the project](#ignoring-parts-of-the-project)
- [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
- [Use case: The adapter pattern](#use-case-the-adapter-pattern)
- [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
- [Shadowed files](#shadowed-files)
- [Edge cases](#edge-cases)
- [Beware of circular dependencies](#beware-of-circular-dependencies)
- [Reopening third-party namespaces](#reopening-third-party-namespaces)
- [Introspection](#introspection)
- [Encodings](#encodings)
- [Rules of thumb](#rules-of-thumb)
- [Debuggers](#debuggers)
- [Pronunciation](#pronunciation)
- [Supported Ruby versions](#supported-ruby-versions)
- [Testing](#testing)
- [Motivation](#motivation)
- [Kernel#require is brittle](#kernelrequire-is-brittle)
- [Rails autoloading was brittle](#rails-autoloading-was-brittle)
- [Awards](#awards)
- [Thanks](#thanks)
- [License](#license)
## Introduction
Zeitwerk is an efficient and thread-safe code loader for Ruby.
Given a [conventional file structure](#file-structure), Zeitwerk is able to load your project's classes and modules on demand (autoloading), or upfront (eager loading). You don't need to write `require` calls for your own files, rather, you can streamline your programming knowing that your classes and modules are available everywhere. This feature is efficient, thread-safe, and matches Ruby's semantics for constants.
Zeitwerk is also able to reload code, which may be handy while developing web applications. Coordination is needed to reload in a thread-safe manner. The documentation below explains how to do this.
The gem is designed so that any project, gem dependency, application, etc. can have their own independent loader, coexisting in the same process, managing their own project trees, and independent of each other. Each loader has its own configuration, inflector, and optional logger.
Internally, Zeitwerk issues `require` calls exclusively using absolute file names, so there are no costly file system lookups in `$LOAD_PATH`. Technically, the directories managed by Zeitwerk do not even need to be in `$LOAD_PATH`.
Furthermore, Zeitwerk does at most one single scan of the project tree, and it descends into subdirectories lazily, only if their namespaces are used.
## Synopsis
Main interface for gems:
```ruby
# lib/my_gem.rb (main file)
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup # ready!
module MyGem
# ...
end
loader.eager_load # optionally
```
Main generic interface:
```ruby
loader = Zeitwerk::Loader.new
loader.push_dir(...)
loader.setup # ready!
```
The `loader` variable can go out of scope. Zeitwerk keeps a registry with all of them, and so the object won't be garbage collected.
You can reload if you want to:
```ruby
loader = Zeitwerk::Loader.new
loader.push_dir(...)
loader.enable_reloading # you need to opt-in before setup
loader.setup
...
loader.reload
```
and you can eager load all the code:
```ruby
loader.eager_load
```
It is also possible to broadcast `eager_load` to all instances:
```ruby
Zeitwerk::Loader.eager_load_all
```
## File structure
### The idea: File paths match constant paths
To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
```
lib/my_gem.rb -> MyGem
lib/my_gem/foo.rb -> MyGem::Foo
lib/my_gem/bar_baz.rb -> MyGem::BarBaz
lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
```
You can tune that a bit by [collapsing directories](#collapsing-directories), or by [ignoring parts of the project](#ignoring-parts-of-the-project), but that is the main idea.
### Inner simple constants
While a simple constant like `HttpCrawler::MAX_RETRIES` can be defined in its own file:
```ruby
# http_crawler/max_retries.rb
HttpCrawler::MAX_RETRIES = 10
```
that is not required, you can also define it the regular way:
```ruby
# http_crawler.rb
class HttpCrawler
MAX_RETRIES = 10
end
```
The first example needs a custom [inflection](#inflection) rule:
```ruby
loader.inflector.inflect("max_retries" => "MAX_RETRIES")
```
Otherwise, Zeitwerk would expect the file to define `MaxRetries`.
In the second example, no custom rule is needed.
### Root directories and root namespaces
Every directory configured with `push_dir` is called a _root directory_, and they represent _root namespaces_.
#### The default root namespace is `Object`
By default, the namespace associated to a root directory is the top-level one: `Object`.
For example, given
```ruby
loader.push_dir("#{__dir__}/models")
loader.push_dir("#{__dir__}/serializers"))
```
these are the expected classes and modules being defined by these files:
```
models/user.rb -> User
serializers/user_serializer.rb -> UserSerializer
```
#### Custom root namespaces
While `Object` is by far the most common root namespace, you can associate a different one to a particular root directory. The method `push_dir` accepts a non-anonymous class or module object in the optional `namespace` keyword argument.
For example, given:
```ruby
require "active_job"
require "active_job/queue_adapters"
loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters)
```
a file defining `ActiveJob::QueueAdapters::MyQueueAdapter` does not need the conventional parent directories, you can (and have to) store the file directly below `adapters`:
```
adapters/my_queue_adapter.rb -> ActiveJob::QueueAdapters::MyQueueAdapter
```
Please, note that the given root namespace must be non-reloadable, though autoloaded constants in that namespace can be. That is, if you associate `app/api` with an existing `Api` module, that module should not be reloadable. However, if the project defines and autoloads the class `Api::Deliveries`, that one can be reloaded.
#### Nested root directories
Root directories should not be ideally nested, but Zeitwerk supports them because in Rails, for example, both `app/models` and `app/models/concerns` belong to the autoload paths.
Zeitwerk detects nested root directories, and treats them as roots only. In the example above, `concerns` is not considered to be a namespace below `app/models`. For example, the file:
```
app/models/concerns/geolocatable.rb
```
should define `Geolocatable`, not `Concerns::Geolocatable`.
### Implicit namespaces
If a namespace is just a simple module with no code, you do not need to define it in a file: Directories without a matching Ruby file get modules created automatically on your behalf.
For example, if a project has an `admin` directory:
```
app/controllers/admin/users_controller.rb -> Admin::UsersController
```
and does not have a file called `admin.rb`, Zeitwerk automatically creates an `Admin` module on your behalf the first time `Admin` is used.
For this to happen, the directory has to contain non-ignored Ruby files with extension `.rb`, directly or recursively, otherwise it is ignored. This condition is evaluated again on reloads.
### Explicit namespaces
Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
```
app/models/hotel.rb -> Hotel
app/models/hotel/pricing.rb -> Hotel::Pricing
```
There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
The classes and modules from the namespace are already available in the body of the class or module defining it:
```ruby
class Hotel < ApplicationRecord
include Pricing # works
...
end
```
An explicit namespace must be managed by one single loader. Loaders that reopen namespaces owned by other projects are responsible for loading their constants before setup.
### Collapsing directories
Say some directories in a project exist for organizational purposes only, and you prefer not to have them as namespaces. For example, the `actions` subdirectory in the next example is not meant to represent a namespace, it is there only to group all actions related to bookings:
```
booking.rb -> Booking
booking/actions/create.rb -> Booking::Create
```
To make it work that way, configure Zeitwerk to collapse said directory:
```ruby
loader.collapse("#{__dir__}/booking/actions")
```
This method accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
You can pass directories and glob patterns. Glob patterns are expanded when they are added, and again on each reload.
To illustrate usage of glob patterns, if `actions` in the example above is part of a standardized structure, you could use a wildcard:
```ruby
loader.collapse("#{__dir__}/*/actions")
```
### Testing compliance
When a managed file is loaded, Zeitwerk verifies the expected constant is defined. If it is not, `Zeitwerk::NameError` is raised.
So, an easy way to ensure compliance in the test suite is to eager load the project:
```ruby
begin
loader.eager_load(force: true)
rescue Zeitwerk::NameError => e
flunk e.message
else
assert true
end
```
## Usage
### Setup
#### Generic
Loaders are ready to load code right after calling `setup` on them:
```ruby
loader.setup
```
This method is synchronized and idempotent.
Customization should generally be done before that call. In particular, in the generic interface you may set the root directories from which you want to load files:
```ruby
loader.push_dir(...)
loader.push_dir(...)
loader.setup
```
#### for_gem
`Zeitwerk::Loader.for_gem` is a convenience shortcut for the common case in which a gem has its entry point directly under the `lib` directory:
```
lib/my_gem.rb # MyGem
lib/my_gem/version.rb # MyGem::VERSION
lib/my_gem/foo.rb # MyGem::Foo
```
Neither a gemspec nor a version file are technically required, this helper works as long as the code is organized using that standard structure.
Conceptually, `for_gem` translates to:
```ruby
# lib/my_gem.rb
require "zeitwerk"
loader = Zeitwerk::Loader.new
loader.tag = File.basename(__FILE__, ".rb")
loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
loader.push_dir(__dir__)
```
If the main module references project constants at the top-level, Zeitwerk has to be ready to load them. Their definitions, in turn, may reference other project constants. And this is recursive. Therefore, it is important that the `setup` call happens above the main module definition:
```ruby
# lib/my_gem.rb (main file)
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup
module MyGem
# Since the setup has been performed, at this point we are already able
# to reference project constants, in this case MyGem::MyLogger.
include MyLogger
end
```
Due to technical reasons, the entry point of the gem has to be loaded with `Kernel#require`, which is the standard way to load a gem. Loading that file with `Kernel#load` or `Kernel#require_relative` won't generally work.
`Zeitwerk::Loader.for_gem` is idempotent when invoked from the same file, to support gems that want to reload (unlikely).
If the entry point of your gem lives in a subdirectory of `lib` because it is reopening a namespace defined somewhere else, please use the generic API to setup the loader, and make sure you check the section [_Reopening third-party namespaces_](#reopening-third-party-namespaces) down below.
Loaders returned by `Zeitwerk::Loader.for_gem` issue warnings if `lib` has extra Ruby files or directories.
For example, if the gem has Rails generators under `lib/generators`, by convention that directory defines a `Generators` Ruby module. If `generators` is just a container for non-autoloadable code and templates, not acting as a project namespace, you need to setup things accordingly.
If the warning is legit, just tell the loader to ignore the offending file or directory:
```ruby
loader.ignore("#{__dir__}/generators")
```
Otherwise, there's a flag to say the extra stuff is OK:
```ruby
Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
```
#### for_gem_extension
Let's suppose you are writing a gem to extend `Net::HTTP` with some niche feature. By [convention](https://guides.rubygems.org/name-your-gem/):
* The gem should be called `net-http-niche_feature`. That is, hyphens for the extended part, a hyphen, and underscores for yours.
* The namespace should be `Net::HTTP::NicheFeature`.
* The entry point should be `lib/net/http/niche_feature.rb`.
* Optionally, the gem could have a top-level `lib/net-http-niche_feature.rb`, but, if defined, that one should have just a `require` call for the entry point.
The top-level file mentioned in the last point is optional. In particular, from
```ruby
gem "net-http-niche_feature"
```
if the hyphenated file does not exist, Bundler notes the conventional hyphenated pattern and issues a `require` for `net/http/niche_feature`.
Gem extensions following the conventions above have a dedicated loader constructor: `Zeitwerk::Loader.for_gem_extension`.
The structure of the gem would be like this:
```ruby
# lib/net-http-niche_feature.rb (optional)
# For technical reasons, this cannot be require_relative.
require "net/http/niche_feature"
# lib/net/http/niche_feature.rb
require "net/http"
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem_extension(Net::HTTP)
loader.setup
module Net::HTTP::NicheFeature
# Since the setup has been performed, at this point we are already able
# to reference project constants, in this case Net::HTTP::NicheFeature::MyMixin.
include MyMixin
end
# lib/net/http/niche_feature/version.rb
module Net::HTTP::NicheFeature
VERSION = "1.0.0"
end
```
`Zeitwerk::Loader.for_gem_extension` expects as argument the namespace being extended, which has to be a non-anonymous class or module object.
If it exists, `lib/net/http/niche_feature/version.rb` is expected to define `Net::HTTP::NicheFeature::VERSION`.
Due to technical reasons, the entry point of the gem has to be loaded with `Kernel#require`. Loading that file with `Kernel#load` or `Kernel#require_relative` won't generally work. This is important if you load the entry point from the optional hyphenated top-level file.
`Zeitwerk::Loader.for_gem_extension` is idempotent when invoked from the same file, to support gems that want to reload (unlikely).
### Autoloading
After `setup`, you are able to reference classes and modules from the project without issuing `require` calls for them. They are all available everywhere, autoloading loads them on demand. This works even if the reference to the class or module is first hit in client code, outside your project.
Let's revisit the example above:
```ruby
# lib/my_gem.rb (main file)
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup
module MyGem
include MyLogger # (*)
end
```
That works, and there is no `require "my_gem/my_logger"`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
### Eager loading
Zeitwerk instances are able to eager load their managed files:
```ruby
loader.eager_load
```
That skips [ignored files and directories](#ignoring-parts-of-the-project).
In gems, the method needs to be invoked after the main namespace has been defined, as shown in [Synopsis](#synopsis).
Eager loading is synchronized and idempotent.
Attempting to eager load without previously calling `setup` raises `Zeitwerk::SetupRequired`.
#### Eager load exclusions
You can tell Zeitwerk that certain files or directories are autoloadable, but should not be eager loaded:
```ruby
db_adapters = "#{__dir__}/my_gem/db_adapters"
loader.do_not_eager_load(db_adapters)
loader.setup
loader.eager_load # won't eager load the database adapters
```
However, that can be overridden with `force`:
```ruby
loader.eager_load(force: true) # database adapters are eager loaded
```
Which may be handy if the project eager loads in the test suite to [ensure project layout compliance](#testing-compliance).
The `force` flag does not affect ignored files and directories, those are still ignored.
#### Eager load directories
The method `Zeitwerk::Loader#eager_load_dir` eager loads a given directory, recursively:
```ruby
loader.eager_load_dir("#{__dir__}/custom_web_app/routes")
```
This is useful when the loader is not eager loading the entire project, but you still need some subtree to be loaded for things to function properly.
Both strings and `Pathname` objects are supported as arguments. If the argument is not a directory managed by the receiver, the method raises `Zeitwerk::Error`.
[Eager load exclusions](#eager-load-exclusions), [ignored files and directories](#ignoring-parts-of-the-project), and [shadowed files](#shadowed-files) are not eager loaded.
`Zeitwerk::Loader#eager_load_dir` is idempotent, but compatible with reloading. If you eager load a directory and then reload, eager loading that directory will load its (current) contents again.
The method checks if a regular eager load was already executed, in which case it returns fast.
Nested root directories which are descendants of the argument are skipped. Those subtrees are considered to be conceptually apart.
Attempting to eager load a directory without previously calling `setup` raises `Zeitwerk::SetupRequired`.
#### Eager load namespaces
The method `Zeitwerk::Loader#eager_load_namespace` eager loads a given namespace, recursively:
```ruby
loader.eager_load_namespace(MyApp::Routes)
```
This is useful when the loader is not eager loading the entire project, but you still need some namespace to be loaded for things to function properly.
The argument has to be a class or module object and the method raises `Zeitwerk::Error` otherwise.
If the namespace is spread over multiple directories in the receiver's source tree, they are all eager loaded. For example, if you have a structure like
```
root_dir1/my_app/routes
root_dir2/my_app/routes
root_dir3/my_app/routes
```
where `root_directory{1,2,3}` are root directories, eager loading `MyApp::Routes` will eager load the contents of the three corresponding directories.
There might exist external source trees implementing part of the namespace. This happens routinely, because top-level constants are stored in the globally shared `Object`. It happens also when deliberately [reopening third-party namespaces](#reopening-third-party-namespaces). Such external code is not eager loaded, the implementation is carefully scoped to what the receiver manages to avoid side-effects elsewhere.
This method is flexible about what it accepts. Its semantics have to be interpreted as: "_If_ you manage this namespace, or part of this namespace, please eager load what you got". In particular, if the receiver does not manage the namespace, it will simply do nothing, this is not an error condition.
[Eager load exclusions](#eager-load-exclusions), [ignored files and directories](#ignoring-parts-of-the-project), and [shadowed files](#shadowed-files) are not eager loaded.
`Zeitwerk::Loader#eager_load_namespace` is idempotent, but compatible with reloading. If you eager load a namespace and then reload, eager loading that namespace will load its (current) descendants again.
The method checks if a regular eager load was already executed, in which case it returns fast.
If root directories are assigned to custom namespaces, the method behaves as you'd expect, according to the namespacing relationship between the custom namespace and the argument.
Attempting to eager load a namespace without previously calling `setup` raises `Zeitwerk::SetupRequired`.
#### Eager load namespaces shared by several loaders
The method `Zeitwerk::Loader.eager_load_namespace` broadcasts `eager_load_namespace` to all loaders.
```ruby
Zeitwerk::Loader.eager_load_namespace(MyFramework::Routes)
```
This may be handy, for example, if a framework supports plugins and a shared namespace needs to be eager loaded for the framework to function properly.
Please, note that loaders only eager load namespaces they manage, as documented above. Therefore, this method does not allow you to eager load namespaces not managed by Zeitwerk loaders.
This method does not require that all registered loaders have `setup` already invoked, since that is out of your control. If there's any in that state, it is simply skipped.
#### Global eager load
If you want to eager load yourself and all dependencies that use Zeitwerk, you can broadcast the `eager_load` call to all instances:
```ruby
Zeitwerk::Loader.eager_load_all
```
This may be handy in top-level services, like web applications.
Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
This method does not accept the `force` flag, since in general it wouldn't be a good idea to force eager loading in 3rd party code.
This method does not require that all registered loaders have `setup` already invoked, since that is out of your control. If there's any in that state, it is simply skipped.
### Loading individual files
The method `Zeitwerk::Loader#load_file` loads an individual Ruby file:
```ruby
loader.load_file("#{__dir__}/custom_web_app/routes.rb")
```
This is useful when the loader is not eager loading the entire project, but you still need an individual file to be loaded for things to function properly.
Both strings and `Pathname` objects are supported as arguments. The method raises `Zeitwerk::Error` if the argument is not a Ruby file, is [ignored](#ignoring-parts-of-the-project), is [shadowed](#shadowed-files), or is not managed by the receiver.
`Zeitwerk::Loader#load_file` is idempotent, but compatible with reloading. If you load a file and then reload, a new call will load its (current) contents again.
If you want to eager load a directory, `Zeitwerk::Loader#eager_load_dir` is more efficient than invoking `Zeitwerk::Loader#load_file` on its files.
### Reloading
#### Configuration and usage
Zeitwerk is able to reload code, but you need to enable this feature:
```ruby
loader = Zeitwerk::Loader.new
loader.push_dir(...)
loader.enable_reloading # you need to opt-in before setup
loader.setup
...
loader.reload
```
There is no way to undo this, either you want to reload or you don't.
Enabling reloading after setup raises `Zeitwerk::Error`. Attempting to reload without having it enabled raises `Zeitwerk::ReloadingDisabledError`. Attempting to reload without previously calling `setup` raises `Zeitwerk::SetupRequired`.
Generally speaking, reloading is useful while developing running services like web applications. Gems that implement regular libraries, so to speak, or services running in testing or production environments, won't normally have a use case for reloading. If reloading is not enabled, Zeitwerk is able to use less memory.
Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
#### Thread-safety
In order to reload safely, no other thread can be autoloading or reloading concurrently. Client code is responsible for this coordination.
For example, a web framework that serves each request in its own thread and has reloading enabled could create a read-write lock on boot like this:
```ruby
require "concurrent/atomic/read_write_lock"
MyFramework::RELOAD_RW_LOCK = Concurrent::ReadWriteLock.new
```
You acquire the lock for reading for serving each individual request:
```ruby
MyFramework::RELOAD_RW_LOCK.with_read_lock do
serve(request)
end
```
Then, when a reload is triggered, just acquire the lock for writing in order to execute the method call safely:
```ruby
MyFramework::RELOAD_RW_LOCK.with_write_lock do
loader.reload
end
```
On reloading, client code has to update anything that would otherwise be storing a stale object. For example, if the routing layer of a web framework stores reloadable controller class objects or instances in internal structures, on reload it has to refresh them somehow, possibly reevaluating routes.
### Inflection
Each individual loader needs an inflector to figure out which constant path would a given file or directory map to. Zeitwerk ships with two basic inflectors, and you can define your own.
#### Zeitwerk::Inflector
Each loader instantiated with `Zeitwerk::Loader.new` has an inflector of this type by default.
This is a very basic inflector that converts snake case to camel case:
```
user -> User
users_controller -> UsersController
html_parser -> HtmlParser
```
The camelize logic can be overridden easily for individual basenames:
```ruby
loader.inflector.inflect(
"html_parser" => "HTMLParser",
"mysql_adapter" => "MySQLAdapter"
)
```
The `inflect` method can be invoked several times if you prefer this other style:
```ruby
loader.inflector.inflect "html_parser" => "HTMLParser"
loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
```
Overrides need to be configured before calling `setup`.
The inflectors of different loaders are independent of each other. There are no global inflection rules or global configuration that can affect this inflector. It is deterministic.
#### Zeitwerk::GemInflector
Each loader instantiated with `Zeitwerk::Loader.for_gem` has an inflector of this type by default.
This inflector is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
The inflectors of different loaders are independent of each other. There are no global inflection rules or global configuration that can affect this inflector. It is deterministic.
#### Custom inflector
The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
```ruby
# frozen_string_literal: true
class MyInflector < Zeitwerk::Inflector
def camelize(basename, abspath)
if basename =~ /\Ahtml_(.*)/
"HTML" + super($1, abspath)
else
super
end
end
end
```
The first argument, `basename`, is a string with the basename of the file or directory to be inflected. In the case of a file, without extension. In the case of a directory, without trailing slash. The inflector needs to return this basename inflected. Therefore, a simple constant name without colons.
The second argument, `abspath`, is a string with the absolute path to the file or directory in case you need it to decide how to inflect the basename. Paths to directories don't have trailing slashes.
Then, assign the inflector:
```ruby
loader.inflector = MyInflector.new
```
This needs to be done before calling `setup`.
If a custom inflector definition in a gem takes too much space in the main file, you can extract it. For example, this is a simple pattern:
```ruby
# lib/my_gem/inflector.rb
module MyGem
class Inflector < Zeitwerk::GemInflector
...
end
end
# lib/my_gem.rb
require "zeitwerk"
require_relative "my_gem/inflector"
loader = Zeitwerk::Loader.for_gem
loader.inflector = MyGem::Inflector.new(__FILE__)
loader.setup
module MyGem
# ...
end
```
Since `MyGem` is referenced before the namespace is defined in the main file, it is important to use this style:
```ruby
# Correct, effectively defines MyGem.
module MyGem
class Inflector < Zeitwerk::GemInflector
# ...
end
end
```
instead of:
```ruby
# Raises uninitialized constant MyGem (NameError).
class MyGem::Inflector < Zeitwerk::GemInflector
# ...
end
```
### Callbacks
#### The on_setup callback
The `on_setup` callback is fired on setup and on each reload:
```ruby
loader.on_setup do
# Ready to autoload here.
end
```
Multiple `on_setup` callbacks are supported, and they run in order of definition.
If `setup` was already executed, the callback is fired immediately.
#### The on_load callback
The usual place to run something when a file is loaded is the file itself. However, sometimes you'd like to be called, and this is possible with the `on_load` callback.
For example, let's imagine this class belongs to a Rails application:
```ruby
class SomeApiClient
class << self
attr_accessor :endpoint
end
end
```
With `on_load`, it is easy to schedule code at boot time that initializes `endpoint` according to the configuration:
```ruby
# config/environments/development.rb
loader.on_load("SomeApiClient") do |klass, _abspath|
klass.endpoint = "https://api.dev"
end
# config/environments/production.rb
loader.on_load("SomeApiClient") do |klass, _abspath|
klass.endpoint = "https://api.prod"
end
```
Some uses cases:
* Doing something with a reloadable class or module in a Rails application during initialization, in a way that plays well with reloading. As in the previous example.
* Delaying the execution of the block until the class is loaded for performance.
* Delaying the execution of the block until the class is loaded because it follows the adapter pattern and better not to load the class if the user does not need it.
`on_load` gets a target constant path as a string (e.g., "User", or "Service::NotificationsGateway"). When fired, its block receives the stored value, and the absolute path to the corresponding file or directory as a string. The callback is executed every time the target is loaded. That includes reloads.
Multiple callbacks on the same target are supported, and they run in order of definition.
The block is executed once the loader has loaded the target. In particular, if the target was already loaded when the callback is defined, the block won't run. But if you reload and load the target again, then it will. Normally, you'll want to define `on_load` callbacks before `setup`.
Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
It is also possible to be called when any constant managed by the loader is loaded:
```ruby
loader.on_load do |cpath, value, abspath|
# ...
end
```
The block gets the constant path as a string (e.g., "User", or "Foo::VERSION"), the value it stores (e.g., the class object stored in `User`, or "2.5.0"), and the absolute path to the corresponding file or directory as a string.
Multiple callbacks like these are supported, and they run in order of definition.
There are use cases for this last catch-all callback, but they are rare. If you just need to understand how things are being loaded for debugging purposes, please remember that `Zeitwerk::Loader#log!` logs plenty of information.
If both types of callbacks are defined, the specific ones run first.
Since `on_load` callbacks are executed right after files are loaded, even if the loading context seems to be far away, in practice **the block is subject to [circular dependencies](#beware-of-circular-dependencies)**. As a rule of thumb, as far as loading order and its interdependencies is concerned, you have to program as if the block was executed at the bottom of the file just loaded.
#### The on_unload callback
When reloading is enabled, you may occasionally need to execute something before a certain autoloaded class or module is unloaded. The `on_unload` callback allows you to do that.
For example, let's imagine that a `Country` class fetches a list of countries and caches them when it is loaded. You might want to clear that cache if unloaded:
```ruby
loader.on_unload("Country") do |klass, _abspath|
klass.clear_cache
end
```
`on_unload` gets a target constant path as a string (e.g., "User", or "Service::NotificationsGateway"). When fired, its block receives the stored value, and the absolute path to the corresponding file or directory as a string. The callback is executed every time the target is unloaded.
`on_unload` blocks are executed before the class is unloaded, but in the middle of unloading, which happens in an unspecified order. Therefore, **that callback should not refer to any reloadable constant because there is no guarantee the constant works there**. Those blocks should rely on objects only, as in the example above, or regular constants not managed by the loader. This remark is transitive, applies to any methods invoked within the block.
Multiple callbacks on the same target are supported, and they run in order of definition.
Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
It is also possible to be called when any constant managed by the loader is unloaded:
```ruby
loader.on_unload do |cpath, value, abspath|
# ...
end
```
The block gets the constant path as a string (e.g., "User", or "Foo::VERSION"), the value it stores (e.g., the class object stored in `User`, or "2.5.0"), and the absolute path to the corresponding file or directory as a string.
Multiple callbacks like these are supported, and they run in order of definition.
If both types of callbacks are defined, the specific ones run first.
#### Technical details
Zeitwerk uses the word "unload" to ease communication and for symmetry with `on_load`. However, in Ruby you cannot unload things for real. So, when does `on_unload` technically happen?
When unloading, Zeitwerk issues `Module#remove_const` calls. Classes and modules are no longer reachable through their constants, and `on_unload` callbacks are executed right before those calls.
Technically, though, the objects themselves are still alive, but if everything is used as expected and they are not stored in any non-reloadable place (don't do that), they are ready for garbage collection, which is when the real unloading happens.
### Logging
Zeitwerk is silent by default, but you can ask loaders to trace their activity. Logging is meant just for troubleshooting, shouldn't normally be enabled.
The `log!` method is a quick shortcut to let the loader log to `$stdout`:
```
loader.log!
```
If you want more control, a logger can be configured as a callable
```ruby
loader.logger = method(:puts)
loader.logger = ->(msg) { ... }
```
as well as anything that responds to `debug`:
```ruby
loader.logger = Logger.new($stderr)
loader.logger = Rails.logger
```
In both cases, the corresponding methods are going to be passed exactly one argument with the message to be logged.
It is also possible to set a global default this way:
```ruby
Zeitwerk::Loader.default_logger = method(:puts)
```
If there is a logger configured, you'll see traces when autoloads are set, files loaded, and modules autovivified. While reloading, removed autoloads and unloaded objects are also traced.
As a curiosity, if your project has namespaces you'll notice in the traces Zeitwerk sets autoloads for _directories_. That's a technique used to be able to descend into subdirectories on demand, avoiding that way unnecessary tree walks.
#### Loader tag
Loaders have a tag that is printed in traces in order to be able to distinguish them in globally logged activity:
```
Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
```
By default, a random tag like the one above is assigned, but you can change it:
```
loader.tag = "grep_me"
```
The tag of a loader returned by `for_gem` is the basename of the root file without extension:
```
Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
```
### Ignoring parts of the project
Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
However, sometimes it might still be convenient to tell Zeitwerk to completely ignore some particular Ruby file or directory. That is possible with `ignore`, which accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
There is an edge case related to nested root directories. Conceptually, root directories are independent source trees. If you ignore a parent of a nested root directory, the nested root directory is not affected. You need to ignore it explictly if you want it ignored too.
Let's see some use cases.
#### Use case: Files that do not follow the conventions
Let's suppose that your gem decorates something in `Kernel`:
```ruby
# lib/my_gem/core_ext/kernel.rb
Kernel.module_eval do
# ...
end
```
`Kernel` is already defined by Ruby so the module cannot be autoloaded. Also, that file does not define a constant path after the path name. Therefore, Zeitwerk should not process it at all.
The extension can still coexist with the rest of the project, you only need to tell Zeitwerk to ignore it:
```ruby
kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
loader.ignore(kernel_ext)
loader.setup
```
You can also ignore the whole directory:
```ruby
core_ext = "#{__dir__}/my_gem/core_ext"
loader.ignore(core_ext)
loader.setup
```
Now, that file has to be loaded manually with `require` or `require_relative`:
```ruby
require_relative "my_gem/core_ext/kernel"
```
and you can do that anytime, before configuring the loader, or after configuring the loader, does not matter.
#### Use case: The adapter pattern
Another use case for ignoring files is the adapter pattern.
Let's imagine your project talks to databases, supports several, and has adapters for each one of them. Those adapters may have top-level `require` calls that load their respective drivers:
```ruby
# my_gem/db_adapters/postgresql.rb
require "pg"
```
but you don't want your users to install them all, only the one they are going to use.
On the other hand, if your code is eager loaded by you or a parent project (with `Zeitwerk::Loader.eager_load_all`), those `require` calls are going to be executed. Ignoring the adapters prevents that:
```ruby
db_adapters = "#{__dir__}/my_gem/db_adapters"
loader.ignore(db_adapters)
loader.setup
```
The chosen adapter, then, has to be loaded by hand somehow:
```ruby
require "my_gem/db_adapters/#{config[:db_adapter]}"
```
Note that since the directory is ignored, the required adapter can instantiate another loader to manage its subtree, if desired. Such loader would coexist with the main one just fine.
#### Use case: Test files mixed with implementation files
There are project layouts that put implementation files and test files together. To ignore the test files, you can use a glob pattern like this:
```ruby
tests = "#{__dir__}/**/*_test.rb"
loader.ignore(tests)
loader.setup
```
### Shadowed files
In Ruby, if you have several files called `foo.rb` in different directories of `$LOAD_PATH` and execute
```ruby
require "foo"
```
the first one found gets loaded, and the rest are ignored.
Zeitwerk behaves in a similar way. If `foo.rb` is present in several root directories (at the same namespace level), the constant `Foo` is autoloaded from the first one, and the rest of the files are not evaluated. If logging is enabled, you'll see something like
```
file #{file} is ignored because #{previous_occurrence} has precedence
```
(This message is not public interface and may change, you cannot rely on that exact wording.)
Even if there's only one `foo.rb`, if the constant `Foo` is already defined when Zeitwerk finds `foo.rb`, then the file is ignored too. This could happen if `Foo` was defined by a dependency, for example. If logging is enabled, you'll see something like
```
file #{file} is ignored because #{constant_path} is already defined
```
(This message is not public interface and may change, you cannot rely on that exact wording.)
Shadowing only applies to Ruby files, namespace definition can be spread over multiple directories. And you can also reopen third-party namespaces if done [orderly](#reopening-third-party-namespaces).
### Edge cases
[Explicit namespaces](#explicit-namespaces) like `Trip` here:
```ruby
# trip.rb
class Trip
include Geolocation
end
# trip/geolocation.rb
module Trip::Geolocation
...
end
```
have to be defined with the `class`/`module` keywords, as in the example above.
For technical reasons, raw constant assignment is not supported:
```ruby
# trip.rb
Trip = Class { ...} # NOT SUPPORTED
Trip = Struct.new { ... } # NOT SUPPORTED
Trip = Data.define { ... } # NOT SUPPORTED
```
This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
### Beware of circular dependencies
In Ruby, you can't have certain top-level circular dependencies. Take for example:
```ruby
# c.rb
class C < D
end
# d.rb
class D
C
end
```
In order to define `C`, you need to load `D`. However, the body of `D` refers to `C`.
Circular dependencies like those do not work in plain Ruby, and therefore do not work in projects managed by Zeitwerk either.
### Reopening third-party namespaces
Projects managed by Zeitwerk can work with namespaces defined by third-party libraries. However, they have to be loaded in memory before calling `setup`.
For example, let's imagine you're writing a gem that implements an adapter for [Active Job](https://guides.rubyonrails.org/active_job_basics.html) that uses AwesomeQueue as backend. By convention, your gem has to define a class called `ActiveJob::QueueAdapters::AwesomeQueue`, and it has to do so in a file with a matching path:
```ruby
# lib/active_job/queue_adapters/awesome_queue.rb
module ActiveJob
module QueueAdapters
class AwesomeQueue
# ...
end
end
end
```
It is very important that your gem _reopens_ the modules `ActiveJob` and `ActiveJob::QueueAdapters` instead of _defining_ them. Because their proper definition lives in Active Job. Furthermore, if the project reloads, you do not want any of `ActiveJob` or `ActiveJob::QueueAdapters` to be reloaded.
Bottom line, Zeitwerk should not be managing those namespaces. Active Job owns them and defines them. Your gem needs to _reopen_ them.
In order to do so, you need to make sure those modules are loaded before calling `setup`. For instance, in the entry file for the gem:
```ruby
# Ensure these namespaces are reopened, not defined.
require "active_job"
require "active_job/queue_adapters"
require "zeitwerk"
# By passing the flag, we acknowledge the extra directory lib/active_job
# has to be managed by the loader and no warning has to be issued for it.
loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
loader.setup
```
With that, when Zeitwerk scans the file system and reaches the gem directories `lib/active_job` and `lib/active_job/queue_adapters`, it detects the corresponding modules already exist and therefore understands it does not have to manage them. The loader just descends into those directories. Eventually will reach `lib/active_job/queue_adapters/awesome_queue.rb`, and since `ActiveJob::QueueAdapters::AwesomeQueue` is unknown, Zeitwerk will manage it. Which is what happens regularly with the files in your gem. On reload, the namespaces are safe, won't be reloaded. The loader only reloads what it manages, which in this case is the adapter itself.
### Introspection
The method `Zeitwerk::Loader#dirs` returns an array with the absolute paths of the root directories as strings:
```ruby
loader = Zeitwerk::Loader.new
loader.push_dir(Pathname.new("/foo"))
loader.dirs # => ["/foo"]
```
This method accepts an optional `namespaces` keyword argument. If truthy, the method returns a hash table instead. Keys are the absolute paths of the root directories as strings. Values are their corresponding namespaces, class or module objects:
```ruby
loader = Zeitwerk::Loader.new
loader.push_dir(Pathname.new("/foo"))
loader.push_dir(Pathname.new("/bar"), namespace: Bar)
loader.dirs(namespaces: true) # => { "/foo" => Object, "/bar" => Bar }
```
By default, ignored root directories are filtered out. If you want them included, please pass `ignored: true`.
These collections are read-only. Please add to them with `Zeitwerk::Loader#push_dir`.
### Encodings
Zeitwerk supports projects whose files and file system are in UTF-8. The encoding of the file system can be checked this way:
```
% ruby -e "puts Encoding.find('filesystem')"
UTF-8
```
The test suite passes on Windows with codepage `Windows-1252` if all the involved absolute paths are ASCII. Other supersets of ASCII may work too, but you have to try.
### Rules of thumb
1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
2. Think the mere existence of a file is effectively like writing a `require` call for them, which is executed on demand (autoload) or upfront (eager load).
3. In that line, if two loaders manage files that translate to the same constant in the same namespace, the first one wins, the rest are ignored. Similar to what happens with `require` and `$LOAD_PATH`, only the first occurrence matters.
4. Projects that reopen a namespace defined by some dependency have to ensure said namespace is loaded before setup. That is, the project has to make sure it reopens, rather than define. This is often accomplished just loading the dependency.
5. Objects stored in reloadable constants should not be cached in places that are not reloaded. For example, non-reloadable classes should not subclass a reloadable class, or mixin a reloadable module. Otherwise, after reloading, those classes or module objects would become stale. Referring to constants in dynamic places like method calls or lambdas is fine.
6. In a given process, ideally, there should be at most one loader with reloading enabled. Technically, you can have more, but it may get tricky if one refers to constants managed by the other one. Do that only if you know what you are doing.
### Debuggers
Zeitwerk works fine with [debug.rb](https://github.com/ruby/debug) and [Break](https://github.com/gsamokovarov/break).
[Byebug](https://github.com/deivid-rodriguez/byebug) is compatible except for an edge case explained in [deivid-rodriguez/byebug#564](https://github.com/deivid-rodriguez/byebug/issues/564).
## Pronunciation
"Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
## Supported Ruby versions
Zeitwerk works with CRuby 2.5 and above.
On TruffleRuby all is good except for thread-safety. Right now, in TruffleRuby `Module#autoload` does not block threads accessing a constant that is being autoloaded. CRuby prevents such access to avoid concurrent threads from seeing partial evaluations of the corresponding file. Zeitwerk inherits autoloading thread-safety from this property. This is not an issue if your project gets eager loaded, or if you lazy load in single-threaded environments. (See https://github.com/oracle/truffleruby/issues/2431.)
JRuby 9.3.0.0 is almost there. As of this writing, the test suite of Zeitwerk passes on JRuby except for three tests. (See https://github.com/jruby/jruby/issues/6781.)
## Testing
In order to run the test suite of Zeitwerk, `cd` into the project root and execute
```
bin/test
```
To run one particular suite, pass its file name as an argument:
```
bin/test test/lib/zeitwerk/test_eager_load.rb
```
Furthermore, the project has a development dependency on [`minitest-focus`](https://github.com/seattlerb/minitest-focus). To run an individual test mark it with `focus`:
```ruby
focus
test "capitalizes the first letter" do
assert_equal "User", camelize("user")
end
```
and run `bin/test`.
## Motivation
### Kernel#require is brittle
Since `require` has global side-effects, and there is no static way to verify that you have issued the `require` calls for code that your file depends on, in practice it is very easy to forget some. That introduces bugs that depend on the load order.
Also, if the project has namespaces, setting things up and getting client code to load things in a consistent way needs discipline. For example, `require "foo/bar"` may define `Foo`, instead of reopen it. That may be a broken window, giving place to superclass mismatches or partially-defined namespaces.
With Zeitwerk, you just name things following conventions and done. Things are available everywhere, and descend is always orderly. Without effort and without broken windows.
### Rails autoloading was brittle
Autoloading in Rails was based on `const_missing` up to Rails 5. That callback lacks fundamental information like the nesting or the resolution algorithm being used. Because of that, Rails autoloading was not able to match Ruby's semantics, and that introduced a [series of issues](https://guides.rubyonrails.org/v5.2/autoloading_and_reloading_constants.html#common-gotchas). Zeitwerk is based on a different technique and fixed Rails autoloading starting with Rails 6.
## Awards
Zeitwerk has been awarded an "Outstanding Performance Award" Fukuoka Ruby Award 2022.
## Thanks
I'd like to thank [@matthewd](https://github.com/matthewd) for the discussions we've had about this topic in the past years, I learned a couple of tricks used in Zeitwerk from him.
Also, would like to thank [@Shopify](https://github.com/Shopify), [@rafaelfranca](https://github.com/rafaelfranca), and [@dylanahsmith](https://github.com/dylanahsmith), for sharing [this PoC](https://github.com/Shopify/autoload_reloader). The technique Zeitwerk uses to support explicit namespaces was copied from that project.
Jean Boussier ([@casperisfine](https://github.com/casperisfine), [@byroot](https://github.com/byroot)) deserves special mention. Jean migrated autoloading in Shopify when Zeitwerk integration in Rails was yet unreleased. His work and positive attitude have been outstanding, and thanks to his feedback the interface and performance of Zeitwerk are way, way better. Kudos man ❤️.
Finally, many thanks to [@schurig](https://github.com/schurig) for recording an [audio file](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3) with the pronunciation of "Zeitwerk" in perfect German. 💯
## License
Released under the MIT License, Copyright (c) 2019–ω Xavier Noria.
zeitwerk-2.6.8/Rakefile 0000664 0000000 0000000 00000000307 14422670021 0015036 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require 'rake/testtask'
task :default => :test
Rake::TestTask.new do |t|
t.test_files = Dir.glob('test/lib/**/test_*.rb')
t.libs << "test"
t.warning = true
end
zeitwerk-2.6.8/bin/ 0000775 0000000 0000000 00000000000 14422670021 0014141 5 ustar 00root root 0000000 0000000 zeitwerk-2.6.8/bin/test 0000775 0000000 0000000 00000000136 14422670021 0015046 0 ustar 00root root 0000000 0000000 #!/bin/bash
if [[ -z $1 ]]; then
bundle exec rake
else
bundle exec rake TEST="$1"
fi
zeitwerk-2.6.8/extras/ 0000775 0000000 0000000 00000000000 14422670021 0014677 5 ustar 00root root 0000000 0000000 zeitwerk-2.6.8/extras/zeitwerk_pronunciation.mp3 0000664 0000000 0000000 00000251163 14422670021 0022144 0 ustar 00root root 0000000 0000000 ID3 vTSS Logic Pro X 10.4.4COM h engiTunNORM 00000537 000004F7 00001508 00001441 000003C6 000003C6 000082B0 00008327 00000392 00000392 COM engiTunSMPB 00000000 00000210 000008E8 0000000000015888 00000000 000121CC 00000000 00000000 00000000 00000000 00000000 00000000 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 @ 7 >@Jc
H0AIhDy֙X,B$D ZMI7l`1`D
LȮKȦ!!E
(&bg"::+L"ȮEc
w"Tb+ur+tr+u髑m|bCȒC@2k011D( ,@=0"#Q: - SH@pg00E4M)',!xq])sJOLiL#y<$қx_sҚdW?3@ @ ͐</{pen:@
=;E4?6{=W%0X
}/
H&
Xc h'n%ܱ؉:62ޣHywm(as=8??؎5z9}mM@Oǒ<f4~.@x&ƈ/)