-
on_loadandon_unloadaccept constant paths with leading colons. For example:loader.on_load('::User') { ... }
-
on_loadandon_unloadvalidate that their input is a constant path. For example:loader.on_load(':User') { ... }
raises
NameError.
-
Replace anonymous block parameters with regular named ones.
Ruby 3.3.0 has a bug: it does not parse anonymous block parameters, which were introduced in Ruby 3.1.
While this is a Ruby bug and people could upgrade to 3.3.1, I prefer users just do not hit this. At the end of the day, it is cosmetic.
-
Adds support for namespace files, nsfiles for short.
If a loader has an nsfile configured (
nilby default):loader.nsfile = 'ns.rb' # must be set before setup
explicit namespaces can be defined by such special file inside their directories:
my_component/ns.rb # MyComponent my_component/widget.rb # MyComponent::WidgetThis may be handy for self-contained units for which a
my_component.rbfile in the parent directory would feel unnatural.If an nsfile is set, you can still define explicit namespaces as always. Both styles can coexist in the project. However, it is an error condition to try to define the same namespace using both conventions.
For further details, please check the documentation for nsfiles.
-
When a file is shadowed because the constant path it maps to already exists, the location of said constant is included in the log message.
-
If available, tree traversal is based on
Dir.scan, which saves syscalls in common platforms. This method is a recent addition to Ruby contributed by @byroot, so you need to be on Rubymasterto leverage this for now. -
Tree traversal is a tad more performant, regardless of the previous point. Gains are marginal when eager loading, because it is dominated by loading the code, but
Zeitwerk::Loader#all_expected_cpathswas 14% faster in some benchmarks, for example. -
README.md documents how to collect autoloaded constants using an
on_loadcallback. -
Internal maintenance.
-
Loaders have to manage disjoint source trees. Therefore, when a root directory is configured Zeitwerk ensures it is not already managed by some other loader. The performance of this validation has been improved.
Thanks to @ngan for sharing some benchmarks that led to revise this logic.
-
The helper
Zeitwerk::Loader#cpath_expected_atdid not work correctly if the inflector had logic that relied on the absolute path of the given file or directory. This has been fixed.This bug was found by Codex.
-
Perpetual internal work.
-
Internal improvements and micro-optimizations.
-
Add stable TruffleRuby to CI.
-
Micro-optimization in a hot path.
-
Raises
Zeitwerk::Errorif an autoloaded constant expected to represent a namespace does not store a class or module object. -
Adds
truffleruby-headto CI, except for autoloading thread-safety (see why in truffleruby/truffleruby#2431).
-
Explicit namespaces can now also be defined using constant assignments.
While constant assignments like
# coordinates.rb Coordinates = Data.define(:x, :y)
worked for most objects, they did not for classes and modules that were also namespaces (i.e., those defined by a file and matching subdirectories). In such cases, their child constants could not be autoloaded.
This limitation has been removed.
-
TracePointis no longer used. -
Requires Ruby 3.2 or later.
Gems that work with previous versions of Zeitwerk also work with this one. If they support Ruby versions older than 3.2 they can specify a relaxed version constraint for Zeitwerk like "~> 2.6", for example.
In client projects, Bundler takes the Ruby requirement into account when resolving dependencies, so
Gemfile.lockwill get one compatible with the Ruby version being used.
- Fixes a bug in which projects reopening the main namespace of a gem dependency managed by its own Zeitwerk loader could not reload the constants they added to that external namespace.
- Fix log message when eager loading a directory ends.
-
Logging prints a message when a directory that was not ignored is skipped anyway because it contains no Ruby files.
-
Internal refactors.
- Internal improvements.
-
Implements
Zeitwerk::Loader#all_expected_cpaths, which returns a hash that maps the absolute paths of the files and directories managed by the receiver to their expected constant paths.Please, check its documentation for further details.
-
There is a new experimental null inflector that simply returns its input unchanged:
loader.inflector = Zeitwerk::NullInflector.new
Projects using this inflector are expected to define their constants in files and directories with names exactly matching them:
User.rb -> User HTMLParser.rb -> HTMLParser Admin/Role.rb -> Admin::RolePlease see its documentation for further details.
-
Documentation improvements.
- Maintenance release with some internal polishing.
- Let
on_loadcallbacks for implicit namespaces autoload other implicit namespaces.
- Improve validation of the values returned by the inflector's
camelize.
-
Given a path as a string or
Pathnameobject,Zeitwerk::Loader#cpath_expected_atreturns a string with the corresponding expected constant path.Some examples, assuming that
app/modelsis a root directory:loader.cpath_expected_at("app/models") # => "Object" loader.cpath_expected_at("app/models/user.rb") # => "User" loader.cpath_expected_at("app/models/hotel") # => "Hotel" loader.cpath_expected_at("app/models/hotel/billing.rb") # => "Hotel::Billing"
This method returns
nilfor some input like ignored files, and may raise errors too. Please check its documentation for further details. -
Zeitwerk::Loader#load_fileraises with a more informative error if given a hidden file or directory. -
Zeitwerk::Loader#eager_load_dirdoes nothing if the argument is a hidden file or directory. This is coherent with its existing behavior for eager load exclusions and ignored paths. Before, that kind of argument would result in a non-deliberateNameError. -
Documentation improvements.
-
The new
Zeitwerk::Loader.for_gem_extensiongives you a loader configured according to the conventions of a gem extension.Please check its documentation for further details.
-
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?returnsnilfor that constant name, andconstantsdoes 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 therequirecall 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::NameErroris 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#dirsfilters ignored root directories out. Please, passignored: trueif 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.
- The new
eager_load_namespacehad a bug when eager loading certain namespaces with collapsed directories. This has been fixed.
-
Controlled errors in a couple of situations:
-
Attempting to eager load or reload without previously invoking
setupnow raisesZeitwerk::SetupRequired. -
The method
Zeitwerk::Loader#push_dirraisesZeitwerk::Errorif 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.
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.
v2.6.2introduced a regression in the logic that checks whether two loaders want to manage the same root directories. It has been fixed.
-
Zeitwerk::Loader#load_fileallows you to load an individual Ruby file. Check its documentation for details. -
Zeitwerk::Loader#eager_load_dirallows you to eager load a directory, recursively. Check its documentation for details. -
Zeitwerk::Loader#eager_load_namespaceallows 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 for details. -
Zeitwerk::Loader.eager_load_namespacebroadcastseager_load_namespaceto all registered loaders. Check its documentation for details. -
Documents shadowed files. They always existed, but were not covered by the documentation.
-
Other assorted documentation improvements.
Zeitwerk::Loader#dirsallows you to introspect the root directories configured in the receiver. Please check its documentation for details.
-
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 it.
However, if you don't do so and have a directory
tasksthat only contains Rake files, arguably that directory is not meant to represent a Ruby module. Before, Zeitwerk would define a top-levelTasksmodule 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 #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_gemissue warnings iflibhas extra, non-ignored Ruby files or directories.This is motivated by existing gems with directories under
libthat 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 for further details.
This method returns an instance of a private subclass of
Zeitwerk::Loadernow, but you cannot rely on the type, just on the interface.
- If a file did not define the expected constant, there was a reload, and there were
on_unloadcallbacks, Zeitwerk still tried to access the constant during reload, which raised. This has been corrected.
- The change introduced in 2.5.2 implied a performance regression that was particularly dramatic in Ruby 3.1. We'll address #198 in a different way.
- When
Module#autoloadtriggers the autovivification of an implicit namespace,$LOADED_FEATURESnow gets the corresponding directory pushed. This is just a tweak to Zeitwerk'sKernel#requiredecoration. That way it acts more like the original, and cooperates better with other potentialKernel#requirewrappers, like Bootsnap's.
- Restores support for namespaces that are not hashable. For example namespaces that override the
hashmethod with a different arity as shown in #188.
-
Requires Ruby 2.5.
-
Deletes the long time deprecated preload API. Instead of:
loader.preload("app/models/user.rb")
just reference the constant on setup:
loader.on_setup { User }
If you want to eager load a namespace, use the constants API:
loader.on_setup do Admin.constants(false).each { |cname| Admin.const_get(cname) } end
-
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.
-
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 for further details.
-
There is a new catch-all
Zeitwerk::Loader#on_loadthat takes no argument and is triggered for all loaded objects: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 for further details.
-
The block of the existing
Zeitwerk::Loader#on_loadreceives also the value stored in the constant, and the absolute path to its corresponding file or directory: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
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: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:
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 for further details.
-
Performance improvements.
-
Documentation improvements.
-
The method
Zeitwerk::Loader#eager_loadaccepts aforceflag:loader.eager_load(force: true)
If passed, eager load exclusions configured with
do_not_eager_loadare 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.
-
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:# 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 for further details.
- Use
__send__instead ofsendinternally.
-
Zeitwerk::Loader#push_dirsupports an optionalnamespacekeyword argument. Pass a class or module object if you want the given root directory to be associated with it instead ofObject. Said class or module object cannot be reloadable. -
The default inflector is even more performant.
-
Saves some unnecessary allocations made internally by MRI. See #125, by @casperisfine.
-
Documentation improvements.
-
Internal code base maintenance.
-
Adds support for collapsing directories.
For example, if
booking/actions/create.rbis meant to defineBooking::Createbecause the subdirectoryactionsis there only for organizational purposes, you can tell Zeitwerk withcollapse:loader.collapse("booking/actions")
The method also accepts glob patterns to support standardized project structures:
loader.collapse("*/actions")
Please check the documentation for more details.
-
Eager loading is idempotent, but now you can eager load again after reloading.
Zeitwerk::NameError#namehas the name of the missing constant now.
-
Zeitwerk raised
NameErrorwhen a managed file did not define its expected constant. Now, it raisesZeitwerk::NameErrorinstead, so it is possible for client code to distinguish that mismatch from a regularNameError.Regarding backwards compatibility,
Zeitwerk::NameErroris a subclass ofNameError.
-
The default inflectors have API to override how to camelize selected basenames:
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
caseexpression. You no longer have to define a custom inflector if that is all you need. -
Documentation improvements.
- Raises
Zeitwerk::NameErrorwith a better error message when a managed file or directory has a name that yields an invalid constant name when inflected.Zeitwerk::NameErroris a subclass ofNameError.
-
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
namemethods. -
Documentation improvements.
- Fixes eager loading nested root directories. The new approach in 2.1.7 introduced a regression.
-
Prevent the inflector from deleting parts un multiword constants whose capitalization is the same. For example,
point_2dshould be inflected asPoint2d, rather thanPoint. 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.
-
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.
-
Failed autoloads raise
NameErroras always, but with a more user-friendly message instead of the original generic one from Ruby. -
Eager loading uses
const_getnow rather thanrequire. 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.
-
Supports deletion of root directories in disk after they've been configured.
push_dirrequires 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.
- Documentation improvements.
- Internal work.
- Calling
reloadwith reloading disabled raisesZeitwerk::ReloadingDisabledError.
- Internal performance work.
loaded_cpathsis gone, you can ask if a constant path is going to be unloaded instead withloader.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).
- Reloading is disabled by default. In order to be able to reload you need to opt-in by calling
loader.enable_reloadingbefore 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.
- Faster reload. If you're using
bootsnap, requires at least version 1.4.2.
- Includes an optimization.
- Fixes concurrent autovivifications.
-
Trace point optimization for singleton classes by @casperisfine. See the use case, explanation, and patch in #24.
-
Zeitwerk::Loader#do_not_eager_loadprovides a way to have autoloadable files and directories that should be skipped when eager loading.
- 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 mimics what happens when there are two files in
$LOAD_PATHwith the same relative name, only the first one is loaded byrequire.
- Bug fix by @casperisfine: If the superclass or one of the ancestors of an explicit namespace
Nhas an autoload set for constantC, andn/c.rbexists, the autoload forN::Cproper could be missed.
-
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.
- After module vivification, the tracer could trigger one unnecessary autoload walk.
- In addition to callables, loggers can now also be any object that responds to
debug, which accepts one string argument.
- Use
pretty_printin the exception message for conflicting directories.
- Two different loaders cannot be managing the same files. Now,
Zeitwerk::Loader#push_dirraisesZeitwerk::ConflictingDirectoryif it detects a conflict.
- New class attribute
Zeitwerk::Loader.default_logger, inherited by newly instantiated loaders. Default isnil. - Traces include the loader tag in the prefix to easily distinguish them.
- Loaders now have a tag.
- Documentation improvements.
- Documentation improvements.
Zeitwerk::Loader#ignoreaccepts 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).
do_not_eager_loadhas been removed, please useignoreto 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.
- Initial beta release.