Git Product home page Git Product logo

zeitwerk's Introduction

Zeitwerk

Gem Version Build Status

Introduction

Zeitwerk is an efficient and thread-safe code loader for Ruby.

Given a conventional file structure, Zeitwerk is capable of loading 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; instead, you can streamline your programming by knowing that your classes and modules are available everywhere. This feature is efficient, thread-safe, and aligns with Ruby's semantics for constants.

Zeitwerk also supports code reloading, which can be useful during web application development. However, coordination is required to reload in a thread-safe manner. The documentation below explains how to achieve this.

The gem is designed to allow any project, gem dependency, or application to have its own independent loader. Multiple loaders can coexist in the same process, each managing its own project tree and operating independently of each other. Each loader has its own configuration, inflector, and optional logger.

Internally, Zeitwerk exclusively uses absolute file names when issuing require calls, eliminating the need for costly file system lookups in $LOAD_PATH. Technically, the directories managed by Zeitwerk don't even need to be in $LOAD_PATH.

Furthermore, Zeitwerk performs a single scan of the project tree at most, lazily descending into subdirectories only when their namespaces are used.

Synopsis

Main interface for gems:

# 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:

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:

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:

loader.eager_load

It is also possible to broadcast eager_load to all instances:

Zeitwerk::Loader.eager_load_all

File structure

The idea: File paths match constant paths

For Zeitwerk to work with your file structure, simply name files and directories after 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 fine-tune this behavior by collapsing directories or ignoring specific 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:

# http_crawler/max_retries.rb
HttpCrawler::MAX_RETRIES = 10

that is not required, you can also define it the regular way:

# http_crawler.rb
class HttpCrawler
  MAX_RETRIES = 10
end

The first example needs a custom inflection rule:

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

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

Although Object is the most common root namespace, you have the flexibility to associate a different one with a specific root directory. The push_dir method accepts a non-anonymous class or module object as the optional namespace keyword argument.

For example, given:

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 provided root namespace must be non-reloadable, while allowing autoloaded constants within that namespace to be reloadable. This means that if you associate the app/api directory with an existing Api module, the module itself should not be reloadable. However, if the project defines and autoloads the Api::Deliveries class, that class can be reloaded.

Nested root directories

Root directories are recommended not to be nested; however, Zeitwerk provides support for nested root directories since in frameworks like Rails, both app/models and app/models/concerns belong to the autoload paths.

Zeitwerk identifies nested root directories and treats them as independent roots. In the given example, concerns is not considered a namespace within app/models. For instance, consider the following file:

app/models/concerns/geolocatable.rb

should define Geolocatable, not Concerns::Geolocatable.

Implicit namespaces

If a namespace consists only of a simple module without any code, there is no need to explicitly define it in a separate file. Zeitwerk automatically creates modules on your behalf for directories without a corresponding Ruby file.

For instance, suppose a project includes 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.

To trigger this behavior, the directory must contain non-ignored Ruby files with the ".rb" extension, either directly or recursively. Otherwise, the directory is ignored. This condition is reevaluated during 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:

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:

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:

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:

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:

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:

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:

# 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(File.dirname(__FILE__))

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:

# 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 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:

loader.ignore("#{__dir__}/generators")

Otherwise, there's a flag to say the extra stuff is OK:

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:

  • 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

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:

# 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:

# 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:

loader.eager_load

That skips ignored files and directories.

In gems, the method needs to be invoked after the main namespace has been defined, as shown in 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:

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:

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.

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:

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, ignored files and directories, and 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:

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_dir{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. 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, ignored files and directories, and 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.

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:

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:

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, is shadowed, 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:

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:

require "concurrent/atomic/read_write_lock"

MyFramework::RELOAD_RW_LOCK = Concurrent::ReadWriteLock.new

You acquire the lock for reading for serving each individual request:

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:

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:

loader.inflector.inflect(
  "html_parser"   => "HTMLParser",
  "mysql_adapter" => "MySQLAdapter"
)

The inflect method can be invoked several times if you prefer this other style:

loader.inflector.inflect "html_parser" => "HTMLParser"
loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"

Overrides have to match exactly directory or file (without extension) basenames. For example, if you configure

loader.inflector.inflect("xml" => "XML")

then the following constants are expected:

xml.rb         -> XML
foo/xml        -> Foo::XML
foo/bar/xml.rb -> Foo::Bar::XML

As you see, any directory whose basename is exactly xml, and any file whose basename is exactly xml.rb are expected to define the constant XML in the corresponding namespace. On the other hand, partial matches are ignored. For example, xml_parser.rb would be inflected as XmlParser because xml_parser is not equal to xml. You'd need an additional override:

loader.inflector.inflect(
  "xml"        => "XML",
  "xml_parser" => "XMLParser"
)

If you need more flexibility, you can define a custom inflector, as explained down below.

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.

Zeitwerk::NullInflector

This is an experimental inflector that simply returns its input unchanged.

loader.inflector = Zeitwerk::NullInflector.new

In a project using this inflector, the names of files and directories are equal to the constants they define:

User.rb       -> User
HTMLParser.rb -> HTMLParser
Admin/Role.rb -> Admin::Role

Point is, you think less. Names that typically need custom configuration like acronyms no longer require your attention. What you see is what you get, simple.

This inflector is experimental since Ruby usually goes for snake case in files and directories. But hey, if you fancy giving it a whirl, go for it!

The null inflector cannot be used in Rails applications because the main autoloader also manages engines. However, you could subclass the default inflector and override camelize to return the basename untouched if it starts with an uppercase letter. Generators would not create the expected file names, but you could still experiment to see how far this approach takes you.

In case-insensitive file systems, this inflector works as long as directory listings return the expected strings. Zeitwerk lists directories using Ruby APIs like Dir.children or Dir.entries.

Custom inflector

The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:

# 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:

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:

# 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:

# Correct, effectively defines MyGem.
module MyGem
  class Inflector < Zeitwerk::GemInflector
    # ...
  end
end

instead of:

# 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:

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:

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:

# 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:

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. 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:

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:

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

loader.logger = method(:puts)
loader.logger = ->(msg) { ... }

as well as anything that responds to debug:

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:

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. This allows descending into subdirectories on demand, thus avoiding 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 the 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 explicitly 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:

# 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:

kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
loader.ignore(kernel_ext)
loader.setup

You can also ignore the whole directory:

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:

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:

# 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:

db_adapters = "#{__dir__}/my_gem/db_adapters"
loader.ignore(db_adapters)
loader.setup

The chosen adapter, then, has to be loaded by hand somehow:

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:

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

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.

Edge cases

Explicit namespaces like Trip here:

# 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:

# 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:

# 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 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:

# 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:

# 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

Zeitwerk::Loader#dirs

The method Zeitwerk::Loader#dirs returns an array with the absolute paths of the root directories as strings:

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:

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.

Zeitwerk::Loader#cpath_expected_at

Given a path as a string or Pathname object, Zeitwerk::Loader#cpath_expected_at returns a string with the corresponding expected constant path.

Some examples, assuming that app/models is 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"

If collapsed is a collapsed directory:

loader.cpath_expected_at("a/b/collapsed/c") # => "A::B::C"
loader.cpath_expected_at("a/b/collapsed")   # => "A::B", edge case
loader.cpath_expected_at("a/b")             # => "A::B"

If the argument corresponds to an ignored file or directory, the method returns nil. Same if the argument is not managed by the loader.

Zeitwerk::Error is raised if the given path does not exist:

loader.cpath_expected_at("non_existing_file.rb") # => Zeitwerk::Error

Zeitwerk::NameError is raised if a constant path cannot be derived from it:

loader.cpath_expected_at("8.rb") # => Zeitwerk::NameError

This method does not parse file contents and does not guarantee files define the returned constant path. It just says which is the expected one.

Zeitwerk::Loader#cpath_expected_at is designed to be used with individual paths. If you want to know all the expected constant paths in the project, please use Zeitwerk::Loader#all_expected_cpaths, documented next.

Zeitwerk::Loader#all_expected_cpaths

The method Zeitwerk::Loader#all_expected_cpaths returns a hash that maps the absolute paths of the files and directories managed by the receiver to their expected constant paths.

Ignored files, hidden files, and files whose extension is not ".rb" are not included in the result. Same for directories, hidden or ignored directories are not included in the result. Additionally, directories that contain no files with extension ".rb" (recursively) are also excluded, since those are not considered to represent Ruby namespaces.

For example, if lib is the root directory of a gem with the following contents:

lib/.DS_Store
lib/my_gem.rb
lib/my_gem/version.rb
lib/my_gem/ignored.rb
lib/my_gem/drivers/unix.rb
lib/my_gem/drivers/windows.rb
lib/my_gem/collapsed/foo.rb
lib/tasks/my_gem.rake

Zeitwerk::Loader#all_expected_cpaths would return (maybe in a different order):

{
  "/.../lib"                           => "Object",
  "/.../lib/my_gem.rb"                 => "MyGem",
  "/.../lib/my_gem"                    => "MyGem",
  "/.../lib/my_gem/version.rb"         => "MyGem::VERSION",
  "/.../lib/my_gem/drivers"            => "MyGem::Drivers",
  "/.../lib/my_gem/drivers/unix.rb"    => "MyGem::Drivers::Unix",
  "/.../lib/my_gem/drivers/windows.rb" => "MyGem::Drivers::Windows",
  "/.../lib/my_gem/collapsed"          => "MyGem"
  "/.../lib/my_gem/collapsed/foo.rb"   => "MyGem::Foo"
}

In the previous example we assume lib/my_gem/ignored.rb is ignored, and therefore it is not present in the returned hash. Also, lib/my_gem/collapsed is a collapsed directory, so the expected namespace at that level is still MyGem (this is an edge case).

The file lib/.DS_Store is hidden, hence excluded. The directory lib/tasks is also not present because it contains no files with extension ".rb".

Directory paths do not have trailing slashes.

The order of the hash entries is undefined.

This method does not parse or execute file contents and does not guarantee files define the corresponding constant paths. It just says which are the expected ones.

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 defines, the namespace. This is often accomplished by loading (e.g., require-ing) 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 and debug.rb are fully compatible if CRuby is ≥ 3.1 (see ruby/debug#558).

Byebug is compatible except for an edge case explained in deivid-rodriguez/byebug#564. Prior to CRuby 3.1, debug.rb has a similar edge incompatibility.

Break is fully compatible.

Pronunciation

"Zeitwerk" is pronounced this way.

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 oracle/truffleruby#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 jruby/jruby#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. To run an individual test mark it with focus:

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. 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 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, @rafaelfranca, and @dylanahsmith, for sharing this PoC. The technique Zeitwerk uses to support explicit namespaces was copied from that project.

Jean Boussier (@casperisfine, @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 for recording an audio file with the pronunciation of "Zeitwerk" in perfect German. 💯

License

Released under the MIT License, Copyright (c) 2019–ω Xavier Noria.

zeitwerk's People

Contributors

aeroastro avatar bjfish avatar byroot avatar casperisfine avatar chriscz avatar cotsog avatar datenreisender avatar exoego avatar fxn avatar guigs avatar henrik avatar hkdnet avatar janbiedermann avatar jcoyne avatar kianmeng avatar krzysiek1507 avatar m-nakamura145 avatar maths22 avatar mfilej avatar nageshlop avatar rafbm avatar ricardotk002 avatar robin850 avatar searls avatar shioyama avatar solnic avatar stevenharman avatar teoljungberg avatar tricknotes avatar xuanxu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zeitwerk's Issues

Error running an example from synopsis

Hi,

I'm playing with this gem by running an example from synopsis:

# lib/my_gem.rb
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup

module MyGem
end

loader.eager_load

By running ruby lib/my_gem.rb I'm getting the below error.

  • ruby --version: ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-darwin17]
  • gem list zeitwerk: zeitwerk (2.1.9)

Am I doing something wrong? Thanks!

Traceback (most recent call last):                 
        14: from lib/my_gem.rb:5:in `<main>'       
        13: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/kernel.rb:16:in `require'
        12: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        11: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        10: from /Users/bruno/data/edu/project/lib/my_gem.rb:2:in `<top (required)>'                  
         9: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:442:in `for_gem'
         8: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/registry.rb:85:in `loader_for_gem'
         7: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/registry.rb:85:in `tap'
         6: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/registry.rb:88:in `block in loader_for_gem'
         5: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:182:in `push_dir'
         4: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:713:in `raise_if_conflicting_directory'
         3: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:713:in `synchronize'
         2: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:714:in `block in raise_if_conflicting_directory'
         1: from /Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:714:in `each'
/Users/bruno/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:717:in `block (2 levels) in raise_if_conflicting_directory': loader (Zeitwerk::Error)

#<Zeitwerk::Loader:0x00007fbf270f66d8
 @autoloaded_dirs=[],
 @autoloads={},
 @eager_load_exclusions=#<Set: {}>,
 @eager_loaded=false,
 @ignored_glob_patterns=#<Set: {}>,
 @ignored_paths=#<Set: {}>,
 @inflector=
  #<Zeitwerk::GemInflector:0x00007fbf270f61b0
   @version_file="/Users/bruno/data/edu/project/lib/my_gem/version.rb">,
 @initialized_at=2019-09-01 00:56:45 +0200,
 @lazy_subdirs={},
 @logger=nil,
 @mutex=#<Thread::Mutex:0x00007fbf270f6250>,
 @mutex2=#<Thread::Mutex:0x00007fbf270f6200>,
 @preloads=[],
 @reloading_enabled=false,
 @root_dirs={},
 @setup=false,
 @tag="my_gem",
 @to_unload={}>


wants to manage directory /Users/bruno/data/edu/project/lib, which is already managed by

#<Zeitwerk::Loader:0x00007fbf2710d978
 @autoloaded_dirs=[],
 @autoloads=
  {"/Users/bruno/data/edu/project/lib/my_gem.rb"=>[Object, :MyGem],
   "/Users/bruno/data/edu/project/lib/project"=>[Object, :Project]},
 @eager_load_exclusions=#<Set: {}>,
 @eager_loaded=false,
 @ignored_glob_patterns=#<Set: {}>,
 @ignored_paths=#<Set: {}>,
 @inflector=
  #<Zeitwerk::GemInflector:0x00007fbf2710d0e0
   @version_file="lib/my_gem/version.rb">,
 @initialized_at=2019-09-01 00:56:45 +0200,
 @lazy_subdirs={"Project"=>["/Users/bruno/data/edu/project/lib/project"]},
 @logger=nil,
 @mutex=#<Thread::Mutex:0x00007fbf2710d220>,
 @mutex2=#<Thread::Mutex:0x00007fbf2710d1d0>,
 @preloads=[],
 @reloading_enabled=false,
 @root_dirs={"/Users/bruno/data/edu/project/lib"=>true},
 @setup=true,
 @tag="my_gem",
 @to_unload={}>

Code reloading issue with multiple classes inside a single file

Hello @fxn 👋 ,

Thanks a lot for Zeitwerk, it's a really cool gem.

I'm opening this issue to check if this is something Zeitwerk should support or our application is just not compliant with the file structure described by the Gem.

We have multiple files that have multiple classes inside, it's especially common for grouping error class inside a single file instead of having a bunch of files.

# application_error.rb

class ApplicationError < StandardError
end

class CustomError < ApplicationError
end

Zeitwerk has issues with reloading this and ruby will throw a TypeError: superclass mismatch for class CustomError. This make sense since CustomError was never marked for autoloading.

Here is a failing test

index dd69b8b..372ab87 100644
--- a/test/lib/zeitwerk/test_reloading.rb
+++ b/test/lib/zeitwerk/test_reloading.rb
@@ -18,6 +18,21 @@ class TestReloading < LoaderTest
     assert loader.reloading_enabled?
   end

+  test "superclass mismatch error" do
+    files = [
+      ["x.rb", "class X; end; class AnotherX < X; end"]
+    ]
+
+    with_setup(files) do
+      assert X
+      assert AnotherX
+
+      loader.reload
+
+      assert X
+    end
+  end
+
   test "reloading works if the flag is set" do
     files = [
       ["x.rb", "X = 1"],         # top-level

Happy to work on finding a fix if you consider that Zeitwerk should handle this case. Thanks!

deleting a folder results in an error

absolutely not blocking but a bit interesting

I deleted my mailers folder and got this:

Errno::ENOENT
No such file or directory @ dir_initialize - /Users/localhostdotdev/src/my-app/app/mailers

Autoloading from subdirectory with same name as ruby file doesn't work

Autoloading doesn't seem to work with a file hierarchy like this:

app/models/book.rb          Book
app/models/book/bla.rb      Book::Bla < Book

How to reproduce:

mkdir /tmp/zw && cd /tmp/zw
rails new .
echo "class Book ; end" > app/models/book.rb
mkdir app/models/book
echo "class Book::Bla < Book ; end" > app/models/book/bla.rb
rails console

Then, trying to access Book::Bla does not autoload app/models/book/bla.rb:

Loading development environment (Rails 6.0.0.beta3)
2.5.1 :001 > Book
 => Book 
2.5.1 :002 > Book::Bla
Traceback (most recent call last):
        1: from (irb):2
NameError (uninitialized constant Book::Bla)

LoadError: cannot load such file

Hi,

I am trying to upgrade from Rails 6 beta 3 to finale but something changed.

My app uses this gem https://github.com/mickael-palma-argus/activestorage-openstack which also uses Zeitwerk (you helped me with it a few months back).

Everything worked fined with 6.0.0.beta3 but now when I start my app with the final 6.0.0 I have this error:

2019-08-23T10:05:47.295556+00:00 heroku[web.1]: Starting process with command `bundle exec puma -C config/puma.rb`
2019-08-23T10:05:49.585702+00:00 app[web.1]: Puma starting in single mode...
2019-08-23T10:05:49.585722+00:00 app[web.1]: * Version 4.1.0 (ruby 2.6.3-p62), codename: Fourth and One
2019-08-23T10:05:49.585724+00:00 app[web.1]: * Min threads: 20, max threads: 20
2019-08-23T10:05:49.585732+00:00 app[web.1]: * Environment: staging
2019-08-23T10:05:51.139101+00:00 heroku[web.1]: State changed from starting to crashed
2019-08-23T10:05:51.121376+00:00 heroku[web.1]: Process exited with status 1
2019-08-23T10:05:51.062382+00:00 app[web.1]: ! Unable to load application: NameError: expected file /usr/local/bundle/gems/activestorage_openstack-0.1.5/lib/active_storage/openstack/version.rb to define constant ActiveStorage::Openstack::Version, but didn't
2019-08-23T10:05:51.062493+00:00 app[web.1]: bundler: failed to load command: puma (/usr/local/bundle/bin/puma)
2019-08-23T10:05:51.062543+00:00 app[web.1]: NameError: expected file /usr/local/bundle/gems/activestorage_openstack-0.1.5/lib/active_storage/openstack/version.rb to define constant ActiveStorage::Openstack::Version, but didn't
2019-08-23T10:05:51.062545+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:17:in `on_file_autoloaded'
2019-08-23T10:05:51.062546+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/kernel.rb:17:in `block in require'
2019-08-23T10:05:51.062548+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/kernel.rb:16:in `tap'
2019-08-23T10:05:51.062549+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/kernel.rb:16:in `require'
2019-08-23T10:05:51.062550+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:351:in `const_get'
2019-08-23T10:05:51.062552+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:351:in `block (2 levels) in eager_load'
2019-08-23T10:05:51.062553+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:662:in `block in ls'
2019-08-23T10:05:51.062554+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `foreach'
2019-08-23T10:05:51.062556+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `ls'
2019-08-23T10:05:51.062557+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:346:in `block in eager_load'
2019-08-23T10:05:51.062559+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:338:in `synchronize'
2019-08-23T10:05:51.062560+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:338:in `eager_load'
2019-08-23T10:05:51.062561+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:449:in `each'
2019-08-23T10:05:51.062563+00:00 app[web.1]: /usr/local/bundle/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:449:in `eager_load_all'
2019-08-23T10:05:51.062564+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/application/finisher.rb:122:in `block in <module:Finisher>'
2019-08-23T10:05:51.062565+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/initializable.rb:32:in `instance_exec'
2019-08-23T10:05:51.062566+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/initializable.rb:32:in `run'
2019-08-23T10:05:51.062568+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/initializable.rb:61:in `block in run_initializers'
2019-08-23T10:05:51.062569+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:228:in `block in tsort_each'
2019-08-23T10:05:51.062570+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
2019-08-23T10:05:51.062571+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:431:in `each_strongly_connected_component_from'
2019-08-23T10:05:51.062573+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:349:in `block in each_strongly_connected_component'
2019-08-23T10:05:51.062574+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:347:in `each'
2019-08-23T10:05:51.062575+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:347:in `call'
2019-08-23T10:05:51.062577+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:347:in `each_strongly_connected_component'
2019-08-23T10:05:51.062578+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:226:in `tsort_each'
2019-08-23T10:05:51.062579+00:00 app[web.1]: /usr/local/lib/ruby/2.6.0/tsort.rb:205:in `tsort_each'
2019-08-23T10:05:51.062581+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/initializable.rb:60:in `run_initializers'
2019-08-23T10:05:51.062582+00:00 app[web.1]: /usr/local/bundle/gems/railties-6.0.0/lib/rails/application.rb:363:in `initialize!'
2019-08-23T10:05:51.062583+00:00 app[web.1]: /app/config/environment.rb:7:in `<top (required)>'
2019-08-23T10:05:51.062585+00:00 app[web.1]: config.ru:5:in `require_relative'
2019-08-23T10:05:51.062586+00:00 app[web.1]: config.ru:5:in `block in <main>'
2019-08-23T10:05:51.062587+00:00 app[web.1]: /usr/local/bundle/gems/rack-2.0.7/lib/rack/builder.rb:55:in `instance_eval'
2019-08-23T10:05:51.062588+00:00 app[web.1]: /usr/local/bundle/gems/rack-2.0.7/lib/rack/builder.rb:55:in `initialize'
2019-08-23T10:05:51.062590+00:00 app[web.1]: config.ru:in `new'
2019-08-23T10:05:51.062591+00:00 app[web.1]: config.ru:in `<main>'
2019-08-23T10:05:51.062592+00:00 app[web.1]: /usr/local/bundle/gems/rack-2.0.7/lib/rack/builder.rb:49:in `eval'
2019-08-23T10:05:51.062594+00:00 app[web.1]: /usr/local/bundle/gems/rack-2.0.7/lib/rack/builder.rb:49:in `new_from_string'
2019-08-23T10:05:51.062595+00:00 app[web.1]: /usr/local/bundle/gems/rack-2.0.7/lib/rack/builder.rb:40:in `parse_file'
2019-08-23T10:05:51.062596+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/configuration.rb:321:in `load_rackup'
2019-08-23T10:05:51.062598+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/configuration.rb:246:in `app'
2019-08-23T10:05:51.062599+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/runner.rb:148:in `load_and_bind'
2019-08-23T10:05:51.062600+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/single.rb:98:in `run'
2019-08-23T10:05:51.062601+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/launcher.rb:188:in `run'
2019-08-23T10:05:51.062603+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/lib/puma/cli.rb:80:in `run'
2019-08-23T10:05:51.062604+00:00 app[web.1]: /usr/local/bundle/gems/puma-4.1.0/bin/puma:10:in `<top (required)>'
2019-08-23T10:05:51.062605+00:00 app[web.1]: /usr/local/bundle/bin/puma:23:in `load'
2019-08-23T10:05:51.062609+00:00 app[web.1]: /usr/local/bundle/bin/puma:23:in `<top (required)>'

It does not appear to be reloading the code on changes.

This issue is in reference to #19 (comment).

Adding code to a controller once the server has loaded does not get executed/updated.

Steps to reproduce:

Expected outcome:

  • print foo to the console

Current work around:

  • add config.autoloader = :classic to config/application.rb

Screencast demonstrating issue:

https://cl.ly/577db63e745a


@fxn here is the Zeitwerk trace https://gist.github.com/cj/ffc8b578412034cebdd410bf534e4ab0

Autoloads not set when new `namespaces` are loaded

Hi @fxn !

I'm playing around with Rails 6.0.0.beta2 and came across this error where
constants inside of a ruby namespace are not being loaded by zeitwerk.

I spent some time debugging this error and it seems like bootsnap is preventing
TracePoint.new(:class) calls from being triggered so zeitwerk doesn't not
set autoloads for constants under that namespace.

Here are some simple steps to reproduce that error and how I was able to make it
run by not requiring bootsnap/setup.

Thank for your amazing work on this project.

Create a brand new rails app*

rails new zeitwerk
cd zeitwerk

Create Admin::Test class*

mkdir app/models/admin
echo 'class Admin; end' > app/models/admin.rb
echo 'class Admin::Test; end' > app/models/admin/test.rb

Enable zeitwerk logger*

echo 'Rails.autoloaders.logger = method(:puts)' >> config/application.rb

Try to print Admin::Test class name

DISABLE_SPRING=true rails runner 'puts Admin::Test.name'
[email protected]: autoload set for ApplicationCable, to be autovivified from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/channels/application_cable
[email protected]: autoload set for ApplicationController, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/controllers/application_controller.rb
[email protected]: autoload set for ApplicationHelper, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/helpers/application_helper.rb
[email protected]: autoload set for ApplicationJob, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/jobs/application_job.rb
[email protected]: autoload set for ApplicationMailer, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/mailers/application_mailer.rb
[email protected]: autoload set for Admin, to be autovivified from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin
[email protected]: autoload set for Admin, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin.rb
[email protected]: autoload set for ApplicationRecord, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/application_record.rb
[email protected]: autoload set for ActionText::TagHelper, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/helpers/action_text/tag_helper.rb
[email protected]: autoload set for ActionText::ContentHelper, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/helpers/action_text/content_helper.rb
[email protected]: autoload set for ActionText::RichText, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/models/action_text/rich_text.rb
[email protected]: autoload set for ActionMailbox::BaseController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/action_mailbox/base_controller.rb
[email protected]: autoload set for ActionMailbox::Ingresses, to be autovivified from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/action_mailbox/ingresses
[email protected]: autoload set for Rails::Conductor, to be autovivified from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/rails/conductor
[email protected]: autoload set for ActionMailbox::IncinerationJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/jobs/action_mailbox/incineration_job.rb
[email protected]: autoload set for ActionMailbox::RoutingJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/jobs/action_mailbox/routing_job.rb
[email protected]: autoload set for ActionMailbox::InboundEmail, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/models/action_mailbox/inbound_email.rb
[email protected]: autoload set for ActiveStorage::DirectUploadsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/direct_uploads_controller.rb
[email protected]: autoload set for ActiveStorage::BaseController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/base_controller.rb
[email protected]: autoload set for ActiveStorage::BlobsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/blobs_controller.rb
[email protected]: autoload set for ActiveStorage::RepresentationsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/representations_controller.rb
[email protected]: autoload set for ActiveStorage::DiskController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/disk_controller.rb
[email protected]: autoload set for ActiveStorage::SetCurrent, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/concerns/active_storage/set_current.rb
[email protected]: autoload set for ActiveStorage::SetBlob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/concerns/active_storage/set_blob.rb
[email protected]: autoload set for ActiveStorage::BaseJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/base_job.rb
[email protected]: autoload set for ActiveStorage::AnalyzeJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/analyze_job.rb
[email protected]: autoload set for ActiveStorage::PurgeJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/purge_job.rb
[email protected]: autoload set for ActiveStorage::Variant, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/variant.rb
[email protected]: autoload set for ActiveStorage::Blob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/blob.rb
[email protected]: autoload set for ActiveStorage::Filename, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/filename.rb
[email protected]: autoload set for ActiveStorage::Variation, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/variation.rb
[email protected]: autoload set for ActiveStorage::Attachment, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/attachment.rb
[email protected]: autoload set for ActiveStorage::Current, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/current.rb
[email protected]: autoload set for ActiveStorage::Preview, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/preview.rb
[email protected]: constant Admin loaded from file /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.

uninitialized constant Admin::Test

Disable bootsnap

sed -i '' "s/require 'bootsnap\/setup'/#require 'bootsnap\/setup'/g" config/boot.rb

Try again ( it worked this time )

DISABLE_SPRING=true rails runner 'puts Admin::Test.name'
[email protected]: autoload set for ApplicationCable, to be autovivified from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/channels/application_cable
[email protected]: autoload set for ApplicationController, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/controllers/application_controller.rb
[email protected]: autoload set for ApplicationHelper, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/helpers/application_helper.rb
[email protected]: autoload set for ApplicationJob, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/jobs/application_job.rb
[email protected]: autoload set for ApplicationMailer, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/mailers/application_mailer.rb
[email protected]: autoload set for Admin, to be autovivified from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin
[email protected]: autoload set for Admin, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin.rb
[email protected]: autoload set for ApplicationRecord, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/application_record.rb
[email protected]: autoload set for ActionText::TagHelper, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/helpers/action_text/tag_helper.rb
[email protected]: autoload set for ActionText::ContentHelper, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/helpers/action_text/content_helper.rb
[email protected]: autoload set for ActionText::RichText, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actiontext-6.0.0.beta2/app/models/action_text/rich_text.rb
[email protected]: autoload set for ActionMailbox::BaseController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/action_mailbox/base_controller.rb
[email protected]: autoload set for ActionMailbox::Ingresses, to be autovivified from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/action_mailbox/ingresses
[email protected]: autoload set for Rails::Conductor, to be autovivified from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/controllers/rails/conductor
[email protected]: autoload set for ActionMailbox::IncinerationJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/jobs/action_mailbox/incineration_job.rb
[email protected]: autoload set for ActionMailbox::RoutingJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/jobs/action_mailbox/routing_job.rb
[email protected]: autoload set for ActionMailbox::InboundEmail, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/actionmailbox-6.0.0.beta2/app/models/action_mailbox/inbound_email.rb
[email protected]: autoload set for ActiveStorage::DirectUploadsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/direct_uploads_controller.rb
[email protected]: autoload set for ActiveStorage::BaseController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/base_controller.rb
[email protected]: autoload set for ActiveStorage::BlobsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/blobs_controller.rb
[email protected]: autoload set for ActiveStorage::RepresentationsController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/representations_controller.rb
[email protected]: autoload set for ActiveStorage::DiskController, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/active_storage/disk_controller.rb
[email protected]: autoload set for ActiveStorage::SetCurrent, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/concerns/active_storage/set_current.rb
[email protected]: autoload set for ActiveStorage::SetBlob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/controllers/concerns/active_storage/set_blob.rb
[email protected]: autoload set for ActiveStorage::BaseJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/base_job.rb
[email protected]: autoload set for ActiveStorage::AnalyzeJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/analyze_job.rb
[email protected]: autoload set for ActiveStorage::PurgeJob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/jobs/active_storage/purge_job.rb
[email protected]: autoload set for ActiveStorage::Variant, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/variant.rb
[email protected]: autoload set for ActiveStorage::Blob, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/blob.rb
[email protected]: autoload set for ActiveStorage::Filename, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/filename.rb
[email protected]: autoload set for ActiveStorage::Variation, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/variation.rb
[email protected]: autoload set for ActiveStorage::Attachment, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/attachment.rb
[email protected]: autoload set for ActiveStorage::Current, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/current.rb
[email protected]: autoload set for ActiveStorage::Preview, to be loaded from /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-6.0.0.beta2/app/models/active_storage/preview.rb
[email protected]: autoload set for Admin::Test, to be loaded from /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin/test.rb
[email protected]: constant Admin loaded from file /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin.rb
[email protected]: constant Admin::Test loaded from file /Users/jairovm/Sites/ruby/rails/tmp/zeitwerk/app/models/admin/test.rb
Admin::Test

VERSIONS

bundle show rails                                                                                                                                                                             [18:14:54]
/usr/local/lib/ruby/gems/2.5.0/gems/rails-6.0.0.beta2

bundle show bootsnap                                                                                                                                                                          [18:14:15]
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.1

bundle show zeitwerk                                                                                                                                                                          [18:15:11]
/usr/local/lib/ruby/gems/2.5.0/gems/zeitwerk-1.3.1

Reload is not worked with roda.

Steps to reproduce

folder directory:

├── app.rb
├── config.ru
├── Gemfile
└── Gemfile.lock

content of config.ru

require 'roda'
require 'zeitwerk'

::Loader = Zeitwerk::Loader.new
::Loader.logger = method(:puts)
::Loader.push_dir(__dir__)
::Loader.setup

run App

content of app.rb

class App < Roda
  route do |r|
    p Loader.reload  # <= i am very ensure this code invoked repeatedly when send request.
    r.root do
      'hello1'
    end
  end
end

content of Gemfile

# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem "roda"
gem 'zeitwerk'

start up server

$: rackup
Zeitwerk@3ff636: autoload set for App, to be loaded from /home/zw963/Kid17/mastering_roda/my_app/app.rb
Zeitwerk@3ff636: constant App loaded from file /home/zw963/Kid17/mastering_roda/my_app/app.rb
[2019-03-17 00:52:12] INFO  WEBrick 1.4.2
[2019-03-17 00:52:12] INFO  ruby 2.6.1 (2019-01-30) [x86_64-linux]
[2019-03-17 00:52:12] INFO  WEBrick::HTTPServer#start: pid=29575 port=9292

first time visit http://127.0.0.1:9292/ in browser

logs:

Zeitwerk@eb920c: App unloaded
Zeitwerk@eb920c: autoload set for App, to be loaded from /home/zw963/Kid17/mastering_roda/my_app/app.rb
true
127.0.0.1 - - [17/Mar/2019:00:53:48 +0800] "GET / HTTP/1.1" 200 6 0.0013

i can see 'hello1' is print in browser, this expected behavior.

change code from 'hello1' to 'hello2' in app.rb, visit http://127.0.0.1:9292/ again

logs:

Zeitwerk@eb920c: autoload for App removed
Zeitwerk@eb920c: autoload set for App, to be loaded from /home/zw963/Kid17/mastering_roda/my_app/app.rb
true
127.0.0.1 - - [17/Mar/2019:00:54:53 +0800] "GET / HTTP/1.1" 200 6 0.0006

expected behavior

browser print "hello2"

actually behavior

browser no change, still "hello1"

Thanks

Namespaced models throw uninitialized constant

i have a little problem with my namespaced models:

# user/identity.rb
class User::Identity < ApplicationRecord
...
end

# user.rb
class User < ApplicationRecord
...
has_many :identities, class_name User::Identity.name
...
end

when i try to start the application with zeitwerk it throws this exeption

Uncaught exception: uninitialized constant User (call 'User.connection' to establish a connection)::Identity

It works with the classic loader. I have the same problem when i try to use a method on User::Identity in a method in the User class.
Do you have an idea? Is it a problem with my code, or in zeitwerk?

Greets
Marcel

Idea: Strict mode?

👋 I'm currently clearing up all the shadowed_files in our app, and I'm thinking: is a log actually enough? I'm concerned that users might re-introduce this kind of problems after I cleared them.

Feels to me that a shadowed file it's very likely to be indicative of an error, or at least not be what the user expect.

Is there legitimate reasons for files to be shadowed? Couldn't we more explicitly throw an error when it happens? Possibly as a Loader#strict = true option?

Are there plans to support transitive module loading?

Hi,
I'm wondering whether it is a plan for zeitwerk to support searching the ancestor chain when reloading modules (or is this supported already?).

I tried reading the code, but unfortunately I'm not sure if I've fully grokked it.

What I am asking is will this gem currently fix rails/rails#28997, is that planned in the future, or is that not planned?

Thanks for the gem, looks like it will solve a lot of problems!

Unclear why the main module should be defined after Zeitwerk setup

The README has the following example code:

zeitwerk/README.md

Lines 59 to 69 in 757dd73

# lib/my_gem.rb (main file)
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup # ready!
module MyGem
# ...
end
loader.eager_load # optionally

Is there any reason for the main module to be declared after Zeitwerk setup? I'm asking that because it prevents gem developers to have the Zeitwerk setup in another file under the main module namespace, like this:

# lib/mygem.rb

module MyGem
end

require 'zeitwerk'
require 'mygem/zeitwerk_inflector'

loader = Zeitwerk::Loader.for_gem
zeitwerk_inflector_abs_path = "#{__dir__}/mygem/zeitwerk_inflector.rb"
loader.inflector = MyGem::ZeitwerkInflector.new
loader.ignore zeitwerk_inflector_abs_path
loader.setup
# lib/mygem/zeitwerk_inflector.rb

class MyGem::ZeitwerkInflector < Zeitwerk::Inflector
  def camelize(basename, _abspath)
    case basename
    when 'mygem'
      'MyGem'
    else
      super
    end
  end
end

Actually, I'm using the setup above in one of my projects and I haven't noticed any issues so far, so I wonder if the instructions order in the example is just accidental or not.

Also, I wonder if loader.eager_load order instruction is accidental or not too 😕

Enable auto-reloader, program behavior not inconsistent with disable it.

Steps to reproduce

folder directory:

├── app.rb
├── config.ru
├── Gemfile
└── Gemfile.lock

content of config.ru

# config.ru
require 'roda'
require 'zeitwerk'

loader = Zeitwerk::Loader.new
# loader.logger = method(:puts)
loader.push_dir(__dir__)
loader.setup

if ENV['RACK_ENV'] == 'production'
  Zeitwerk::Loader.eager_load_all
  run App
else
  run ->(env) {
    loader.reload
    App.call(env)
  }
end

content of app.rb

class App < Roda
  articles = []

  route do |r|
    r.post "articles" do
      articles << r.params["content"]
      "Count: #{articles.count}"
    end
  end
end

start server, and post http://127.0.0.1:9292/articles?content='content' repeatly.

Expected behavior

When no enable zeitwerk, We can see Following output:

POST articles?content='content'
# => Count: 1
POST articles?content='content'
# => Count: 2
POST articles?content='content'
# => Count: 3
...

Actual behavior

POST articles?content='content'
# => Count: 1
POST articles?content='content'
# => Count: 1
POST articles?content='content'
# => Count: 1
...

Disappearing instance methods

During upgrade to Rails 6.0.0.beta2 I found a problem with zeitwerk autoloader, which results in non present instance methods on controller that actually is defined and works fine with "classic" autoloader.

I reproduced it here https://github.com/morgoth/bug with steps described in the readme.

Maybe it's more a Rails problem, but since it strictly connects with switching autoloader I'm opening it here.

Zeitwerk doesn't auto reload our code even with enable_reloading set to "true"

We're using Grape + ActiveRecord combo as our API service. Gems/Zeitwerk initializer looks like this:

# environment.rb

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __FILE__)
ENV['RACK_ENV'] ||= 'development'

require 'bundler' and Bundler.require(:default, ENV['RACK_ENV'])
loader = Zeitwerk::Loader.new
%w(api models helpers lib).each { |dir| loader.push_dir(dir) }
loader.enable_reloading unless ENV['RACK_ENV'] == 'production'
loader.setup

later we call this code in our Rack app:

require_relative 'environment'

# mount Grape app, etc.

We want auto code reloading to work in development environment which is default in our setup. Current environment is defined by RACK_ENV env variable, no RAILS_ENV is used.

For some reason this setup doesn't work. Changes made to files in api, lib or other directories don't trigger code reloading. I believe there is no issue in Zeitwerk code, we're just missing something. Is it because of the absence of RAILS_ENV variable? We'd like to figure it out.

Zeitwerk trying to autoload YAML files since 2.1.9

Since upgrading to Rails 6 from 6.rc2, I'm getting an error whereby Zeitwerk is truing to autoload a YAML file placed in `my-rails-app/some-dir/some-subdir/1-my-file.yml.

Framework trace is:

NameError: wrong constant name 1-my-file
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:705:in `const_defined?'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:705:in `cdef?'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:610:in `strict_autoload_path'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:587:in `autoload_for?'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:501:in `autoload_subdir'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:490:in `block in set_autoloads_in_dir'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:662:in `block in ls'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `foreach'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `ls'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:476:in `set_autoloads_in_dir'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:67:in `block in on_namespace_loaded'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:66:in `each'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:66:in `on_namespace_loaded'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:52:in `block in on_dir_autoloaded'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:39:in `synchronize'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader/callbacks.rb:39:in `on_dir_autoloaded'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/kernel.rb:20:in `require'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:355:in `const_get'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:355:in `block (2 levels) in eager_load'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:662:in `block in ls'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `foreach'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:659:in `ls'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:346:in `block in eager_load'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:338:in `synchronize'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:338:in `eager_load'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:449:in `each'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:449:in `eager_load_all'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/application/finisher.rb:122:in `block in <module:Finisher>'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/initializable.rb:32:in `instance_exec'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/initializable.rb:32:in `run'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/initializable.rb:61:in `block in run_initializers'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:228:in `block in tsort_each'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:431:in `each_strongly_connected_component_from'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:349:in `block in each_strongly_connected_component'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `each'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `call'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `each_strongly_connected_component'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:226:in `tsort_each'
~/.rbenv/versions/2.6.3/lib/ruby/2.6.0/tsort.rb:205:in `tsort_each'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/initializable.rb:60:in `run_initializers'
~/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/railties-6.0.0/lib/rails/application.rb:363:in `initialize!'

Puzzling frozen array for unloadable_cpaths.

I'm not sure if this should be logged here or in ActiveSupport, given it's overlapping between the two… but also, I'm not entirely across the interplay of all of this anyway.

I've noticed that the value for unloadable_cpaths is a frozen array. This is passed through to Rails as the initial autoloaded_constants value in ActiveSupport::Dependencies - but the logic there modifies the provided array (with uniq! and concat calls in particular). At a high level, I'm finding this confusing - why provide a frozen object for something where modifications are expected?

On a more tangible/practical level: Thinking Sphinx (a gem I maintain) loads all files within app/indices (to find index definitions) using ActiveSupport::Dependencies.require_or_load file. When this occurs in Rails 6.0.0.rc1, a FrozenError crops up, because the underlying modifications to autoloaded_constants are being attempted on that initial frozen value (as noted in pat/thinking-sphinx#1137).

So: is this a bug in Zeitwerk/ActiveSupport? Or am I misusing/misunderstanding ActiveSupport::Dependencies in Thinking Sphinx? Or something else entirely? :)

zeitwerk (1.4.3) Rails 6 beta 3, killer bug

So I did bundle update and it went as usual, like a butter. Then I started rails server changed lot of things and took 20 trials to zero down to this gem. To reproduce, just change any controller or model or any rb file, no matter what the change is, even if there is no change (change-save undo-save), then the weird errors like constant User is undefined started popping out. Basically whole app code got lost. If you restart server it works again, until you make a first rb file related change, same again. Reverted to 1.4.2 to avoid this hell.

Zeitwerk is not compatible with Rails Inflector

I have some defined acronyms in config/inflections.rb which are used in namespaces. Typically something like Id => ID

If I have the following concern app/models/concerns/my_acronym/test.rb where I have module MyACRONYM::Test. Then I include this concern in app/models/application_record.rb like include MyACRONYM::Test. With the classic autoloader it works but not with Zeitwerk. I'm getting uninitialized constant MyACRONYM::Test (NameError).

This happens after Rails 5.2 => 6.0 upgrade.

Better support for adapter pattern and optional source files in general (never eager load instead of ignore totally)

Background

Adapter is a popular design pattern in Ruby. Quite often, adapters rely on some optional dependencies, for example Active Record's SQLite3Adapter starts with following lines:

gem "sqlite3", "~> 1.3", ">= 1.3.6"
require "sqlite3"

(from rails/rails)

Consequently, adapter source file must be loaded conditionally, which isn't fully supported by Zeitwerk — not when a gem or application is supposed to be loaded eagerly. Zeitwerk's README explains how to workaround it:

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:

db_adapters = "#{__dir__}/my_gem/db_adapters"
loader.ignore(db_adapters)
loader.setup

The chosen adapter, then, has to be loaded by hand somehow:

require "my_gem/db_adapters/#{config[:db_adapter]}"

However, this basically means: do not use Zeitwerk for adapters at all. Switch back to old require instead, and resign from all the benefits Zeitwerk provides, including code reloading. I believe this could be improved.

Proposal

IMHO optional source files should be handled by Zeitwerk. The only thing what must be done in order to resolve this problem is to exclude them from being loaded eagerly. My proposal is to define a method Loader#exclude_from_eager_loading, which would work as in a following example:

db_adapters = "#{__dir__}/my_gem/db_adapters"
loader.exclude_from_eager_loading(db_adapters)
loader.setup

Then, given there is an adapter named MyGem::DbAdapters::MyAdapter defined in a source file my_gem/db_adapters/my_adapter.rb:

  • calling loader.eager_load would not load that source file;
  • referencing MyGem::DbAdapters::MyAdapter would load that source file, regardless if loader.eager_load has been called previously or not;
  • calling loader.preload("my_gem/db_adapters/my_adapter.rb") would also load that source file;

Also, perhaps it's worth to add an argument to #eager_load method, so that:

  • calling loader.eager_load(optional: true) would load that source file as well;

WDYT?

Failing with extension gem

Hi folks,

Given I have a extension gem (using dashes in the name), for example my-gem(My::Gem), how to correct setup the zeitwerk?

I made the following test and it's failing!

    files = [
      ["my/gem.rb", <<-EOS],
        $for_gem_test_loader = Zeitwerk::Loader.for_gem
        $for_gem_test_loader.enable_reloading
        $for_gem_test_loader.setup

        module My
          module Gem
          end
        end
      EOS
      ["my/gem/foo.rb", "class My::Gem::Foo; end"],
      ["my/gem/foo/bar.rb", "class My::Gem::Foo::Bar; end"]
    ]
    with_files(files) do
      with_load_path(".") do
        assert require "my/gem"
        assert My::Gem::Foo::Bar

        $for_gem_test_loader.unload
        assert !Object.const_defined?(:My::Gem)

        $for_gem_test_loader.setup
        assert My::Gem::Foo::Bar
      end
    end
% rake test                                                                                                                                                  *master zeitwerk

# Running tests with run options --seed 48021:

......................................................................E..........................................................................

Finished tests in 1.354945s, 107.0154 tests/s, 249.4567 assertions/s.


Error:
TestForGem#test_sets_my_gem_correctly:
NameError: uninitialized constant My::Gem::Foo
    /home/duke/src/oss/zeitwerk/test/lib/zeitwerk/test_for_gem.rb:49:in `block (3 levels) in <class:TestForGem>'
    /home/duke/src/oss/zeitwerk/test/support/loader_test.rb:70:in `with_load_path'
    /home/duke/src/oss/zeitwerk/test/lib/zeitwerk/test_for_gem.rb:47:in `block (2 levels) in <class:TestForGem>'
    /home/duke/src/oss/zeitwerk/test/support/loader_test.rb:61:in `block in with_files'
    /home/duke/src/oss/zeitwerk/test/support/loader_test.rb:54:in `chdir'
    /home/duke/src/oss/zeitwerk/test/support/loader_test.rb:54:in `with_files'
    /home/duke/src/oss/zeitwerk/test/lib/zeitwerk/test_for_gem.rb:46:in `block in <class:TestForGem>'

145 tests, 338 assertions, 0 failures, 1 errors, 0 skips
rake aborted!
Command failed with status (1)

Tasks: TOP => test
(See full trace by running task with --trace)

Can somebody help me to understand why zeitwerk aren't working? I'm making something wrong or it's a bug?

Acronyms

What's the recommended way to define classes/modules that contain (or are entirely) acronyms?

For example (form 1):

lib/http.rb => Http
lib/smtp.rb => Smtp
lib/uri.rb  => Uri

This works, but in stdlib such names are defined as HTTP, SMTP and URI. This style guide also recommends keeping acronyms uppercase.

For example (form 2):

lib/h_t_t_p.rb => HTTP
lib/s_m_t_p.rb => SMTP
lib/u_r_i.rb   => URI

This also works, but the file names now look quite unusual.

What is the recommended way to deal with this?

  • Use form 1?
  • Use form 2?
  • Somehow combine form 1 (file name) with form 2 (class name)?

Thanks!

Autoload doesn't work in Rails 6 and app folder

Hello. I try to make the following naming pattern: app/api/endpoint.rb to resolve to Api::Endpoint.
I know, that this is a pretty uncommon pattern, but it works well on Rails 5.2 with the classic autoloader.

What I do:

    config.autoload_paths += Dir[Rails.root.join('app')]
    config.eager_load_paths += Dir[Rails.root.join('app')]

in my application.rb, but Api namespace can't be resolved, I get:

NameError (uninitialized constant Api)

It works well if I put api/endpoint.rb to the project root, add root folder to autoload_paths, as well, as If I put to app/lib/api/endpoint.rb.


irb(main):005:0> pp Rails.autoloaders.main
#<Zeitwerk::Loader:0x00007ff9792b07a8
 @autoloaded_dirs=[],
 @autoloads=
  {"/home/sergiy/Work/Doormat/doormat-server/app/javascript"=>
    [Object, :Javascript],
   "/home/sergiy/Work/Doormat/doormat-server/app/views"=>[Object, :Views],
   "/home/sergiy/Work/Doormat/doormat-server/app/assets"=>[Object, :Assets],
   "/home/sergiy/Work/Doormat/doormat-server/app/api/root.rb"=>[Object, :Root],
   "/home/sergiy/Work/Doormat/doormat-server/app/channels/application_cable"=>
    [Object, :ApplicationCable],
   "/home/sergiy/Work/Doormat/doormat-server/app/controllers/application_controller.rb"=>
    [Object, :ApplicationController],
   "/home/sergiy/Work/Doormat/doormat-server/app/helpers/application_helper.rb"=>
    [Object, :ApplicationHelper],
   "/home/sergiy/Work/Doormat/doormat-server/app/jobs/application_job.rb"=>
    [Object, :ApplicationJob],
   "/home/sergiy/Work/Doormat/doormat-server/app/mailers/application_mailer.rb"=>
    [Object, :ApplicationMailer],
   "/home/sergiy/Work/Doormat/doormat-server/app/models/application_record.rb"=>
    [Object, :ApplicationRecord],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/grape-swagger-rails-0.3.1/app/controllers/grape_swagger_rails/application_controller.rb"=>
    [GrapeSwaggerRails, :ApplicationController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actiontext-6.0.0.rc1/app/helpers/action_text/tag_helper.rb"=>
    [ActionText, :TagHelper],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actiontext-6.0.0.rc1/app/helpers/action_text/content_helper.rb"=>
    [ActionText, :ContentHelper],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actiontext-6.0.0.rc1/app/models/action_text/rich_text.rb"=>
    [ActionText, :RichText],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers/action_mailbox/ingresses"=>
    [ActionMailbox, :Ingresses],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers/action_mailbox/base_controller.rb"=>
    [ActionMailbox, :BaseController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers/rails/conductor"=>
    [Rails, :Conductor],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/jobs/action_mailbox/incineration_job.rb"=>
    [ActionMailbox, :IncinerationJob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/jobs/action_mailbox/routing_job.rb"=>
    [ActionMailbox, :RoutingJob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/models/action_mailbox/inbound_email.rb"=>
    [ActionMailbox, :InboundEmail],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/active_storage/direct_uploads_controller.rb"=>
    [ActiveStorage, :DirectUploadsController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/active_storage/base_controller.rb"=>
    [ActiveStorage, :BaseController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/active_storage/disk_controller.rb"=>
    [ActiveStorage, :DiskController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/active_storage/blobs_controller.rb"=>
    [ActiveStorage, :BlobsController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/active_storage/representations_controller.rb"=>
    [ActiveStorage, :RepresentationsController],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/concerns/active_storage/set_current.rb"=>
    [ActiveStorage, :SetCurrent],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/concerns/active_storage/set_blob.rb"=>
    [ActiveStorage, :SetBlob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/jobs/active_storage/purge_job.rb"=>
    [ActiveStorage, :PurgeJob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/jobs/active_storage/base_job.rb"=>
    [ActiveStorage, :BaseJob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/jobs/active_storage/analyze_job.rb"=>
    [ActiveStorage, :AnalyzeJob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/current.rb"=>
    [ActiveStorage, :Current],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/blob.rb"=>
    [ActiveStorage, :Blob],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/attachment.rb"=>
    [ActiveStorage, :Attachment],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/filename.rb"=>
    [ActiveStorage, :Filename],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/variation.rb"=>
    [ActiveStorage, :Variation],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/preview.rb"=>
    [ActiveStorage, :Preview],
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/variant.rb"=>
    [ActiveStorage, :Variant]},
 @eager_load_exclusions=#<Set: {}>,
 @eager_loaded=false,
 @ignored=#<Set: {}>,
 @ignored_paths=#<Set: {}>,
 @inflector=ActiveSupport::Dependencies::ZeitwerkIntegration::Inflector,
 @initialized_at=2019-06-29 17:10:40 +0300,
 @lazy_subdirs=
  {"Javascript"=>["/home/sergiy/Work/Doormat/doormat-server/app/javascript"],
   "Views"=>["/home/sergiy/Work/Doormat/doormat-server/app/views"],
   "Assets"=>["/home/sergiy/Work/Doormat/doormat-server/app/assets"],
   "ApplicationCable"=>
    ["/home/sergiy/Work/Doormat/doormat-server/app/channels/application_cable"],
   "ActionMailbox::Ingresses"=>
    ["/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers/action_mailbox/ingresses"],
   "Rails::Conductor"=>
    ["/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers/rails/conductor"],
   "ActionMailbox::InboundEmail"=>
    ["/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/models/action_mailbox/inbound_email"],
   "ActiveStorage::Blob"=>
    ["/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models/active_storage/blob"]},
 @logger=nil,
 @mutex=#<Thread::Mutex:0x00007ff9792b03c0>,
 @mutex2=#<Thread::Mutex:0x00007ff9792b0398>,
 @preloads=[],
 @reloading_enabled=true,
 @root_dirs=
  {"/home/sergiy/Work/Doormat/doormat-server/app"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/api"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/channels"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/controllers"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/controllers/concerns"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/helpers"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/jobs"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/mailers"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/models"=>true,
   "/home/sergiy/Work/Doormat/doormat-server/app/models/concerns"=>true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/grape-swagger-rails-0.3.1/app/controllers"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actiontext-6.0.0.rc1/app/helpers"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actiontext-6.0.0.rc1/app/models"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/controllers"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/jobs"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.0.rc1/app/models"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/controllers/concerns"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/jobs"=>
    true,
   "/home/sergiy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activestorage-6.0.0.rc1/app/models"=>
    true},
 @setup=true,
 @shadowed_files=#<Set: {}>,
 @tag="rails.main",
 @to_unload={}>

QUESTION: convention for declaring name spaced classes

I posted this over on stackoverflow already but figured I might get more traction here.
Hopefully posting questions and not issues here is ok.

Curious what the preferred name spaced code should look like in rails 6 which uses zeitwerk for autoloading.

Previously I used:

# app/controllers/api/users_controller.rb
module Api
  class UsersController
    def index
      render json: {}
    end
  end 
end

With zeitwerk should we now use: ???

# app/controllers/api/users_controller.rb
class Api::UsersController
  def index
    render json: {}
  end 
end

Based on example in https://weblog.rubyonrails.org/2019/2/22/zeitwerk-integration-in-rails-6-beta-2/ it appears the 2nd style is being used.

By default rubocop will raise Style/ClassAndModuleChildren error with 2nd style and there are slight behavior differences:

module Foo
  class Bar
    def fud
    end
  end
end

module Foo
  class Woo
    def woo_woo
      Bar.new.fud
    end
  end
end
class Foo::Bar
  def fud
  end
end

class Foo::Woo
  def woo_woo
    # NameError: uninitialized constant Foo::Woo::Bar
    Bar.new.fud
    # no error
    Foo::Bar.new.fud
  end
end

From:
https://stackoverflow.com/questions/56675838/rails-6-convention-for-declaring-namespaced-classes-zeitwerk-autoloader

Reload from nested subdirectories

Hello there and thank you for the awesome work with this gem. I'm trying this on a non-rails project and have some issues with code-reloading. It loads the files just fine but wont reload them and I cannot see them in the @autoloads array.

My directory structure is:

apps
  web
    controllers
      books.rb
# apps/web/controllers/books.rb

module Web::Controllers
  class Books
    # ...
  end
end

My loader is setup like this:

loader = Zeitwerk::Loader.new
loader.push_dir("/path/to/lib")
loader.push_dir("/path/to/apps")
loader.setup

# And in a middleware I call (it's the same instance as the one above)
loader.reload

The files in lib gets reloaded but not in apps. If I would guess this has something to do with the "empty" namespace between Web::Controllers.

Am I missing something, has this something to do with the rails concerns compatibility?

This is what I get when I inspect the loader:

#<Zeitwerk::Loader:0x00007fdb978cf198 @inflector=#<Zeitwerk::Inflector:0x00007fdb978cf148>, @dirs={"/path/to/sandbox/lib"=>true, "/path/to/sandbox/apps"=>true}, @preloads=[], @ignored=#<Set: {}>, @autoloads={"/path/to/sandbox/lib/sandbox/message.rb"=>[Sandbox, "Message"], "/path/to/sandbox/apps/web"=>[Object, "Web"]}, @lazy_subdirs={"Web"=>["/path/to/sandbox/apps/web"]}, @eager_load_exclusions=#<Set: {}>, @mutex=#<Thread::Mutex:0x00007fdb978cef40>, @setup=true, @eager_loaded=false, @tracer=#<TracePoint:enabled>>

-

please delete

const_defined?': wrong constant name Font-awesome (NameError)

Hi we are using rails version 6.0.0 and when i run using rails version 6.0.0.rc1 its working fine
Error log
home/system/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:705:inconst_defined?': wrong constant name Font-awesome (NameError)
`

Reloading, autoloading and thread safety

Hi there!

At first, thanks for such a great project! We're finally able to overcome Rails autoloading gotchas and, moreover, bring autoloading and reloading to our non-Rails projects.

Appreciate your outstanding work! I've watched your presentation on Stuart-Tech and was even more inspired.

At the moment I'm experimenting with Zeitwerk + Rack (Cuba). Autoloading works like a charm but I have an issue with code reloading in a multithreaded environment. The docs say that reloading itself is not thread-safe and it's my responsibility to coordinate it which definitely makes sense.

To be able to reload code between requests in Rack I've implemented a very trivial middleware:

  class Reloader
    def initialize(app, loader)
      @app = app
      @loader = loader
      @mutex = Mutex.new
    end

    def call(env)
      @mutex.synchronize { @loader.reload }
      @app.call(env)
    end
  end

Unfortunately, it doesn't help and I still see errors like that:

web_1      | 2019-05-15 04:36:43 +0000: Rack app error handling request { GET /sidekiq/stylesheets/bootstrap.css }
web_1      | #<ArgumentError: wrong number of arguments (given 0, expected 2)>
web_1      | /bundle/gems/zeitwerk-2.1.6/lib/zeitwerk/loader.rb:655:in `cpath'
web_1      | /bundle/gems/zeitwerk-2.1.6/lib/zeitwerk/loader/callbacks.rb:11:in `on_file_autoloaded'
web_1      | /bundle/gems/zeitwerk-2.1.6/lib/zeitwerk/kernel.rb:17:in `block in require'
web_1      | /bundle/gems/zeitwerk-2.1.6/lib/zeitwerk/kernel.rb:16:in `tap'
web_1      | /bundle/gems/zeitwerk-2.1.6/lib/zeitwerk/kernel.rb:16:in `require'
web_1      | /bundle/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `block in require'
web_1      | /bundle/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:257:in `load_dependency'
web_1      | /bundle/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `require'
web_1      | /app/config/routes.rb:24:in `block (3 levels) in <top (required)>'  # `SidekiqAdmin` class should be loaded on that line
# Unrelated stack

It happens because cref is not resolved from empty, for some reason, autoloads

It happens once and after that, there are code loading issues after the exception:

web_1      | Zeitwerk@ed7a8d: file /app/app/web/controllers/sidekiq_admin.rb is ignored because SidekiqAdmin is already defined

Does it mean that the autoloading is not thread-safe for some reason?

I assume that becasue when I wrap not only reloading, but also the constant loading in a lock, the problem goes away.

Simplified:

    def call(env)
      @mutex.synchronize do
         @loader.reload
         @app.call(env)
      end
    end

Are partially loaded classes visible?

Very interestingly looking project! I am curios, does the thread-safety property also guaranty that no other thread will see partially loaded class? Consider thread A, which triggers loading of a file defining class C. Then can a thread B which evaluates constant C while A is still lading the file defining C see the class C partially defined? As I read the code I think it might happen. Did you consider providing thread-safety for this as well?

Why does the project require ruby 2.4 and above? Are there technical difficulties to make it work with older Ruby versions?

Question on File Structure Best Practices

Hi, I have question regarding the best practices for file structure (ref)

In my Rails project, I organize lengthy constant declarations into separate files in order to keep classes clean.

For example:

# app/models/foo.rb
class Foo
end

# app/models/foo/constants.rb
class Foo
  MY_CONSTANT = ...
end

# elsewhere in app
Foo::MY_CONSTANT

However, Zeitwerk doesn't like this because it maps from filenames to constants, and requires those constants to be defined (ref). So, if you try to load the code above, you'll get an error message:

Excpeted file app/models/foo/constants.rb to define constant Foo::Constants, but didn't.

The obvious solution here is to define Foo::Constants:

# app/models/foo/constants.rb
class Foo
  module Constants
    MY_CONSTANT = ...
  end
end

# elsewhere in app
Foo::Constants::MY_CONSTANT

But, I have a lot of files like foo/constants.rb, and I am lazy. Are there any other alternatives for getting zeitwerk to autoload files like this?

I appreciate the work the team has done in this gem! It's a big improvement.

Unintuitive Inflector Behavior

You might want to consider using capitalize instead of capitalize! in Inflector.
capitalize! returns nil if nothing has been changed which causes an entire part of the name to be swallowed.
e.g. point_3d_value is camelized to PointValue

Loader wants to manage directory which is already managed

I have two gems. One called dor-services which knows nothing of zeitwerk and one called dor-services-client. The latter is a dependency of the former. The latter does use zeitwerk. When I run tests for dor-services I now get:

Failure/Error: require 'dor/services/client'

Zeitwerk::Error:
  loader

  #<Zeitwerk::Loader:0x00007fdd1e44f2e8
   @autoloaded_dirs=[],
   @autoloads={},
   @eager_load_exclusions=#<Set: {}>,
   @eager_loaded=false,
   @ignored=#<Set: {}>,
   @ignored_paths=#<Set: {}>,
   @inflector=#<DorServicesClientInflector:0x00007fdd1e44ef78>,
   @initialized_at=2019-05-23 15:53:38 -0500,
   @lazy_subdirs={},
   @logger=nil,
   @mutex=#<Thread::Mutex:0x00007fdd1e44efc8>,
   @mutex2=#<Thread::Mutex:0x00007fdd1e44efa0>,
   @preloads=[],
   @reloading_enabled=false,
   @root_dirs={},
   @setup=false,
   @shadowed_files=#<Set: {}>,
   @tag="1157b8",
   @to_unload={}>


  wants to manage directory /Users/jcoyne85/workspace/sul-dlss/dor-services/lib, which is already managed by

  #<Zeitwerk::Loader:0x00007fdd1d887c30
   @autoloaded_dirs=[],
   @autoloads=
    {"/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/tasks"=>
      [Object, :Tasks],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/indexers"=>
      [Dor, :Indexers],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/exceptions.rb"=>
      [Dor, :Exceptions],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/utils"=>
      [Dor, :Utils],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/models"=>
      [Dor, :Models],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/workflow"=>
      [Dor, :Workflow],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/release_tags.rb"=>
      [Dor, :ReleaseTags],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/config.rb"=>
      [Dor, :Config],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/version.rb"=>
      [Dor, :Version],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/services"=>
      [Dor, :Services],
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/datastreams"=>
      [Dor, :Datastreams]},
   @eager_load_exclusions=#<Set: {}>,
   @eager_loaded=false,
   @ignored=#<Set: {}>,
   @ignored_paths=#<Set: {}>,
   @inflector=#<DorServicesClientInflector:0x00007fdd1d8877a8>,
   @initialized_at=2019-05-23 15:53:37 -0500,
   @lazy_subdirs=
    {"Tasks"=>["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/tasks"],
     "Dor::Indexers"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/indexers"],
     "Dor::Utils"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/utils"],
     "Dor::Models"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/models"],
     "Dor::Workflow"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/workflow"],
     "Dor::ReleaseTags"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/release_tags"],
     "Dor::Services"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/services"],
     "Dor::Datastreams"=>
      ["/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/datastreams"]},
   @logger=nil,
   @mutex=#<Thread::Mutex:0x00007fdd1d8877f8>,
   @mutex2=#<Thread::Mutex:0x00007fdd1d8877d0>,
   @preloads=[],
   @reloading_enabled=false,
   @root_dirs={"/Users/jcoyne85/workspace/sul-dlss/dor-services/lib"=>true},
   @setup=false,
   @shadowed_files=
    #<Set: {"/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/certificate_authenticated_rest_resource_factory.rb",
     "/Users/jcoyne85/workspace/sul-dlss/dor-services/lib/dor/rest_resource_factory.rb"}>,
   @tag="8029fe",
   @to_unload={}>

Question Conflict File Path with gem

Hi, I have question Conflict File Path with gem.

In my Rails project, I want to load Model class.
But raise uninitialized constant error.

I want to know best practices for conflict File Path with gem

For example:

# MyRailsApp/app/models/foo.rb in my Rails project
require "MyRailsApp/vendor/bundle/ruby/2.5.0/bundler/gems/hoge-gem/app/models/foo.rb"
class Foo
end

# vendor/bundle/ruby/2.5.0/bundler/gems/hoge-gem/app/models/foo.rb

class Foo
end
$ rails c
[1] pry(main)> Foo
NameError: uninitialized constant Foo
Did you mean?  Foo
from (pry):1:in `<main>'

I append infomation If loss of infomation.

Zeitwerk will setup twice

reproduce steps (with ruby 2.6.1):

Gemfile:

source 'https://rubygems.org'
ruby '~> 2.6'
gem 'zeitwerk', '~> 2.1.2'

lib/foo.rb:

require 'zeitwerk'
loader = Zeitwerk::Loader.for_gem
loader.setup

module Foo; end

Run bundle exec ruby lib/foo.rb and get errors below:

Traceback (most recent call last):
        15: from lib/foo.rb:5:in `<main>'
        14: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/kernel.rb:16:in `require'
        13: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/kernel.rb:16:in `require'
        12: from /tmp/foo/lib/foo.rb:2:in `<top (required)>'
        11: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:417:in `for_gem'
        10: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/registry.rb:85:in `loader_for_gem'
         9: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/registry.rb:85:in `tap'
         8: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/registry.rb:88:in `block in loader_for_gem'
         7: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:187:in `push_dir'
         6: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:678:in `raise_if_conflicting_directory'
         5: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:678:in `synchronize'
         4: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:679:in `block in raise_if_conflicting_directory'
         3: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:679:in `each'
         2: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:682:in `block (2 levels) in raise_if_conflicting_directory'
         1: from /home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:682:in `each'
/home/davy/.rvm/gems/ruby-2.6.1/gems/zeitwerk-2.1.2/lib/zeitwerk/loader.rb:685:in `block (3 levels) in raise_if_conflicting_directory': loader (Zeitwerk::Error)

#<Zeitwerk::Loader:0x00000000021473d0
 @autoloaded_dirs=[],
 @autoloads={},
 @eager_load_exclusions=#<Set: {}>,
 @eager_loaded=false,
 @ignored=#<Set: {}>,
 @ignored_paths=#<Set: {}>,
 @inflector=
  #<Zeitwerk::GemInflector:0x0000000002158860
   @version_file=
    "/tmp/foo/lib/foo/version.rb">,
 @initialized_at=2019-04-15 16:40:21 +0800,
 @lazy_subdirs={},
 @logger=nil,
 @mutex=#<Thread::Mutex:0x0000000002144158>,
 @mutex2=#<Thread::Mutex:0x0000000002144108>,
 @preloads=[],
 @reloading_enabled=false,
 @root_dirs={},
 @setup=false,
 @shadowed_files=#<Set: {}>,
 @tag="foo",
 @to_unload={}>


wants to manage directory /tmp/foo/lib, which is already managed by

#<Zeitwerk::Loader:0x0000000002155e80
 @autoloaded_dirs=[],
 @autoloads=
  {"/tmp/foo/lib/foo.rb"=>[Object, "Foo"]},
 @eager_load_exclusions=#<Set: {}>,
 @eager_loaded=false,
 @ignored=#<Set: {}>,
 @ignored_paths=#<Set: {}>,
 @inflector=
  #<Zeitwerk::GemInflector:0x000000000217b978
   @version_file="lib/foo/version.rb">,
 @initialized_at=2019-04-15 16:40:21 +0800,
 @lazy_subdirs={},
 @logger=nil,
 @mutex=#<Thread::Mutex:0x0000000002154c38>,
 @mutex2=#<Thread::Mutex:0x0000000002154b48>,
 @preloads=[],
 @reloading_enabled=false,
 @root_dirs={"/tmp/foo/lib"=>true},
 @setup=true,
 @shadowed_files=#<Set: {}>,
 @tag="foo",
 @to_unload={}>

It seems lib/foo.rb loaded again when loader.setup called and caused another loader setups, and this caused crashes

Eager loading problem in version 2.1.5 (also in classic autoloader)

I have a few apps using Camaleon CMS, which is a Rails engine. When I tried to upgrade from Rails 5.2.3 to 6.0.0rc1, eager loading broke and the app won't boot with it turned on.

I realize this could be seen as an issue with Camaleon, but there appears to be a regression from 2.1.4 to 2.1.5.

I also was under the impression that setting the autoloader to :classic should preserve pre-6.0 behavior, but that is not the case as things that load fine in 5.2 do not load correctly in classic mode.

Symptoms:

  • not working with Zeitwerk 2.1.5
  • not working with config.autoloader = :classic
  • working with Zeitwerk 2.1.4 (non-classic mode only)

Repro here: https://github.com/brian-kephart/zeitwerk_issue. Steps:

  • git clone https://github.com/brian-kephart/zeitwerk_issue.git
  • bundle
  • rails s (app should boot)
  • comment out the zeitwerk entry in the Gemfile and bundle update zeitwerk, or uncomment config.autoloader = :classic in application.rb, and the app will no longer boot.

zeitwerk-2.1.9, ruby-2.5.5, Rails 6.0 upgrade uninitialized constant ApplicationJob (NameError)

First of all, thank you so much for tackling autoloading.

When upgrading a large Rails 5.2 app, I'm encountering the following:

.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/zeitwerk-2.1.9/lib/zeitwerk/loader.rb:351:in const_get': uninitialized constant ApplicationJob (NameError) Did you mean? ApplicationJob

After enabling the log, it happens when zeitwerk starts loading the jobs folder in the Rails app.
The folder contains a file "application_job.rb" with the following content:
class ApplicationJob < ActiveJob::Base queue_as :default end

As this is a quite common pattern, I wonder what the correct way of declaration and usage of such Base Wrapper classes is in order for the autoloading to pick up on it. I also wonder, why the class name is picked up by the typo suggestion below the error output but not Zeitwerk.

Is this a matter of load order, do extensions of Rails Base classes need to be placed in a different namespace or loaded before-hand?

open class for override in reload case is not supported

ruby: 2.6.2
rails: 6.0.0.beta3

I have a model defined in my engine:

# app/models/rails_org/member.rb
class Member < ApplicationRecord
end

I overrided it in my main project

# app/models/member.rb
require 'rails_org/member'
class Member < ApplicationRecord
end

in reload case, only delete main model defined path from $LOADED_FEATURES

Sorry for my poor english, if need more information, please point out.

Append subdir to root namespace?

My use case is a gem. I would like to have the constants defined in its models/ directory belong to the root namespace, like so:

lib/my_gem.rb                         -> MyGem
lib/my_gem/models/flip.rb             -> MyGem::Flip
lib/my_gem/models/flop.rb             -> MyGem::Flop
lib/my_gem/models/concerns/widget.rb  -> MyGem::Widget
lib/my_gem/bar/flip.rb                -> MyGem::Bar::Flip
lib/my_gem/bar/flop.rb                -> MyGem::Bar::Flop

Is this possible?

eager_load difference between autoloader classic, bug or feature?

Hi,

I noticed that when I used config.eager_load=true or ran the Jumpstart template in production which overrides the Devise helper https://github.com/excid3/jumpstart/blob/c6c0de0a9493c617297746ebef99a061f05c1518/app/helpers/devise_helper.rb it was not getting used. If I however switched to config.autoloader = :classic everything worked as expected.

Is this a bug or a feature?

Steps to reproduce:

Step 1:

Step 2:

Step 3:

Step 4:

  • kill foreman
  • add config.autoloader = :classic to config/application.rb
  • Repeat Step 2 and it will be the correct boostrap error message again.

I'm going to also reference excid3/jumpstart#73 and loop in @excid3.

uninitialized constant Concerns (NameError)

For version 2.1.7, when I run rails application as production mode like below
RAILS_ENV=production rails s

zeit raises exception like below
uninitialized constant Concerns (NameError)

It works fine on 2.1.6.

I only have .keep files under all concerns directories.

Fallback for older Ruby versions

Could zeitwerk provide a fallback that would eager load everything (probably also with disabled reloading) on Ruby implementations which do not fulfill the zeitwerk's requirements? That would potentially allow for wider adoption.

I am considering to use it in concurrent-ruby. It still supports 1.9 so I need a fallback, I started thinking about adding fallback in concurrent-ruby however it seems it would be better and beneficial to have in the zeitwerk itself.

Zeitwerk 2.1.5 breaks: uninitialized constant

Zeitwerk 2.1.5 can raise an “uninitialized constant” error while 2.1.4 works fine.

Steps to reproduce

OK:

  1. Clone https://github.com/ddfreyne/zeitwerk-nanoc-core-mini
  2. Run bundle (this installs Zeitwerk 2.1.4)
  3. Run bundle exec ruby test.rb

This prints

I am the thing! I exist!
Nanoc::Core::Thing

Let’s make it fail:

  1. Change the zeitwerk line in Gemfile to gem 'zeitwerk', '= 2.1.5' (was = 2.1.4)
  2. Run bundle
  3. Run bundle exec ruby test.rb

This prints

`const_get': uninitialized constant NanocCore (NameError)

Expected results

Same behavior as Zeitwerk 2.1.4.

Actual results

Raises uninitialized constant NanocCore (NameError)

Extra details

Traceback:

Traceback (most recent call last):
	13: from test.rb:5:in `<main>'
	12: from test.rb:5:in `require'
	11: from /Users/denis/Desktop/zeitwerk-nanoc-core-mini/lib/nanoc-core.rb:3:in `<top (required)>'
	10: from /Users/denis/Desktop/zeitwerk-nanoc-core-mini/lib/nanoc-core.rb:3:in `require'
	 9: from /Users/denis/Desktop/zeitwerk-nanoc-core-mini/lib/nanoc/core.rb:20:in `<top (required)>'
	 8: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:341:in `eager_load'
	 7: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:341:in `synchronize'
	 6: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:348:in `block in eager_load'
	 5: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:631:in `each_abspath'
	 4: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:631:in `foreach'
	 3: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:634:in `block in each_abspath'
	 2: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:352:in `block (2 levels) in eager_load'
	 1: from /usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:669:in `const_get_if_autoload'
/usr/local/lib/ruby/gems/2.6.0/gems/zeitwerk-2.1.5/lib/zeitwerk/loader.rb:669:in `const_get': uninitialized constant NanocCore (NameError)

Loader error on ignored paths

Steps to reproduce:

# my_gem
loader = Zeitwerk::Loader.for_gem
loader.ignore 'lib/foo/bar'
loader.setup

Later, in another file:

# lib/foo/bar/zoo/my_file
loader = Zeitwerk::Loader.new
loader.push_dir "#{__dir__}/active_record" # <= raised here
loader.setup

It looks like the problem is in Loade::raise_if_conflicting_directory(dir) method. Don't you mind if I'll take it for PR?

Clockwork on Heroku is failing to load

Clockwork Gem - https://github.com/Rykian/clockwork

Getting this error - ! Unable to load application: NameError: expected file /app/lib/clock.rb to define constant Clock, but didn't

My clock.rb is inside - /APP_ROOT/lib/clock.rb, and not in /APP_ROOT/app/lib/clock.rb

This is my environment on Heroku -

  • Rails v6.0
  • Ruby v2.6.4
  • Zeitwerk v2.1.10

Detailed Error -

2019-09-20T01:16:52.504423+00:00 app[web.1]: ! Unable to load application: NameError: expected file /app/lib/clock.rb to define constant Clock, but didn't
2019-09-20T01:16:52.504612+00:00 app[web.1]: bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.6.0/bin/puma)
2019-09-20T01:16:52.504669+00:00 app[web.1]: NameError: expected file /app/lib/clock.rb to define constant Clock, but didn't
2019-09-20T01:16:52.504672+00:00 app[web.1]: /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.1.10/lib/zeitwerk/loader/callbacks.rb:17:in `on_file_autoloaded'
2019-09-20T01:16:52.504674+00:00 app[web.1]: /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.1.10/lib/zeitwerk/kernel.rb:17:in `block in require'
2019-09-20T01:16:52.504678+00:00 app[web.1]: /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.1.10/lib/zeitwerk/kernel.rb:16:in `tap'
2019-09-20T01:16:52.504681+00:00 app[web.1]: /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.1.10/lib/zeitwerk/kernel.rb:16:in `require'

Adding more info here -

This issue is fixed if I use classic autoloader as suggested here - https://weblog.rubyonrails.org/2019/2/22/zeitwerk-integration-in-rails-6-beta-2/

config.autoloader = :classic

Also,
I have the following in application.rb - config.eager_load_paths += %W[#{config.root}/lib]

Performance issue in CI

Hi there!

I don't know if it's the right place for this issue, but Rails bug tracker is very busy so I open it here :)

My issue : I've tested my Rails app with Rails 6.0.0.beta2 and tried the new Zeitgest loader, and noticed that my test suite duration is twice longer than before (in Gitlab CI env) :/

The context :

  1. I use grosser/parallel_tests to run the test suite with 6 cpus, and usually it takes 6/7mn to run.

  2. Last week I introduced Zeitwerk in a bunch of gems I use (simple_navigation_bootstrap, active_settings) and noticed that the tests were a bit longer but didn't dig into it.

  3. Finally, I've set up Zeitwerk in 9 gems that I use in this app, and noticed that the test suite was really longer : it took 12/13mn to run.

  4. Now I use Zeitwerk in the Rails app and the test suite take 30mn to run 😢

By reverting the Rails loader to the classic mode it takes 13mn to run.

I could remove Zeitwerk in the gems I use and run some tests and I'm pretty sure it will solve the issue.
But I don't think it's the right direction to go.

Maybe I should eager load everything in CI env?

What do you think?

Thank you!

autoloading "Helpers-like" modules

Hi,

Here is the folder tree my gem has:

lib
├── active_storage
│   ├── openstack
│   │   ├── client
│   │   │   ├── authenticator
│   │   │   │   └── request.rb
│   │   │   ├── authenticator.rb
│   │   │   ├── storage
│   │   │   │   ├── delete_object.rb
│   │   │   │   ├── get_object.rb
│   │   │   │   ├── list_objects.rb
│   │   │   │   ├── object_store_url.rb
│   │   │   │   ├── put_object.rb
│   │   │   │   └── show_object_metadata.rb
│   │   │   └── storage.rb
│   │   ├── client.rb
│   │   ├── helpers
│   │   │   ├── cache_readerable.rb
│   │   │   ├── cacheable_body.rb
│   │   │   └── https_client.rb
│   │   ├── railtie.rb
│   │   └── version.rb
│   └── service
│       └── openstack_service.rb
└── activestorage_openstack.rb

In the activestorage_openstack.rb file I put:

require 'zeitwerk'
Zeitwerk::Loader.for_gem.setup

In the authenticator.rb file, I have:

require_relative '../helpers/cache_readerable'

module ActiveStorage
  module Openstack
    class Client
      class Authenticator
        include Helpers::CacheReaderable
        [...]
      end
    end
  end
end

I want to get rid of the require_relative directive but without it I get this error:

NameError:
  uninitialized constant ActiveStorage::Openstack::Helpers::CacheReaderable

Any suggestions?

Thank you for the work so far.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.