zeitwerk 2.2.0 → 2.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -3,36 +3,75 @@
3
3
 
4
4
 
5
5
  [![Gem Version](https://img.shields.io/gem/v/zeitwerk.svg?style=for-the-badge)](https://rubygems.org/gems/zeitwerk)
6
- [![Build Status](https://img.shields.io/travis/com/fxn/zeitwerk/master?style=for-the-badge)](https://travis-ci.com/fxn/zeitwerk)
6
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/fxn/zeitwerk/ci.yml?branch=main&event=push&style=for-the-badge)](https://github.com/fxn/zeitwerk/actions/workflows/ci.yml?query=branch%3Amain)
7
+
7
8
 
8
9
  <!-- TOC -->
9
10
 
10
11
  - [Introduction](#introduction)
11
12
  - [Synopsis](#synopsis)
12
13
  - [File structure](#file-structure)
13
- - [Implicit namespaces](#implicit-namespaces)
14
- - [Explicit namespaces](#explicit-namespaces)
14
+ - [The idea: File paths match constant paths](#the-idea-file-paths-match-constant-paths)
15
+ - [Inner simple constants](#inner-simple-constants)
16
+ - [Root directories and root namespaces](#root-directories-and-root-namespaces)
17
+ - [The default root namespace is `Object`](#the-default-root-namespace-is-object)
18
+ - [Custom root namespaces](#custom-root-namespaces)
15
19
  - [Nested root directories](#nested-root-directories)
20
+ - [Implicit namespaces](#implicit-namespaces)
21
+ - [Explicit namespaces](#explicit-namespaces)
22
+ - [Explicit namespaces defined in ordinary files](#explicit-namespaces-defined-in-ordinary-files)
23
+ - [Explicit namespaces defined in nsfiles](#explicit-namespaces-defined-in-nsfiles)
24
+ - [Collapsing directories](#collapsing-directories)
25
+ - [Testing compliance](#testing-compliance)
16
26
  - [Usage](#usage)
17
- - [Setup](#setup)
18
- - [Reloading](#reloading)
19
- - [Eager loading](#eager-loading)
20
- - [Inflection](#inflection)
21
- - [Zeitwerk::Inflector](#zeitwerkinflector)
22
- - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
23
- - [Custom inflector](#custom-inflector)
24
- - [Logging](#logging)
25
- - [Loader tag](#loader-tag)
26
- - [Ignoring parts of the project](#ignoring-parts-of-the-project)
27
- - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
28
- - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
29
- - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
30
- - [Edge cases](#edge-cases)
31
- - [Rules of thumb](#rules-of-thumb)
32
- - [Autoloading, explicit namespaces, and debuggers](#autoloading-explicit-namespaces-and-debuggers)
27
+ - [Setup](#setup)
28
+ - [Generic](#generic)
29
+ - [for_gem](#for_gem)
30
+ - [for_gem_extension](#for_gem_extension)
31
+ - [Autoloading](#autoloading)
32
+ - [Eager loading](#eager-loading)
33
+ - [Eager load exclusions](#eager-load-exclusions)
34
+ - [Eager load directories](#eager-load-directories)
35
+ - [Eager load namespaces](#eager-load-namespaces)
36
+ - [Eager load namespaces shared by several loaders](#eager-load-namespaces-shared-by-several-loaders)
37
+ - [Global eager load](#global-eager-load)
38
+ - [Loading individual files](#loading-individual-files)
39
+ - [Reloading](#reloading)
40
+ - [Configuration and usage](#configuration-and-usage)
41
+ - [Thread-safety](#thread-safety)
42
+ - [Inflection](#inflection)
43
+ - [Zeitwerk::Inflector](#zeitwerkinflector)
44
+ - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
45
+ - [Zeitwerk::NullInflector](#zeitwerknullinflector)
46
+ - [Custom inflector](#custom-inflector)
47
+ - [Callbacks](#callbacks)
48
+ - [The on_setup callback](#the-on_setup-callback)
49
+ - [The on_load callback](#the-on_load-callback)
50
+ - [The on_unload callback](#the-on_unload-callback)
51
+ - [Technical details](#technical-details)
52
+ - [Logging](#logging)
53
+ - [Loader tag](#loader-tag)
54
+ - [Ignoring parts of the project](#ignoring-parts-of-the-project)
55
+ - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
56
+ - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
57
+ - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
58
+ - [Shadowed files](#shadowed-files)
59
+ - [Beware of circular dependencies](#beware-of-circular-dependencies)
60
+ - [Reopening third-party namespaces](#reopening-third-party-namespaces)
61
+ - [Introspection](#introspection)
62
+ - [`Zeitwerk::Loader#dirs`](#zeitwerkloaderdirs)
63
+ - [Autoloaded Constants](#autoloaded-constants)
64
+ - [`Zeitwerk::Loader#cpath_expected_at`](#zeitwerkloadercpath_expected_at)
65
+ - [`Zeitwerk::Loader#all_expected_cpaths`](#zeitwerkloaderall_expected_cpaths)
66
+ - [Encodings](#encodings)
67
+ - [Rules of thumb](#rules-of-thumb)
33
68
  - [Pronunciation](#pronunciation)
34
69
  - [Supported Ruby versions](#supported-ruby-versions)
70
+ - [Testing](#testing)
35
71
  - [Motivation](#motivation)
72
+ - [Kernel#require is brittle](#kernelrequire-is-brittle)
73
+ - [Rails autoloading was brittle](#rails-autoloading-was-brittle)
74
+ - [Awards](#awards)
36
75
  - [Thanks](#thanks)
37
76
  - [License](#license)
38
77
 
@@ -43,13 +82,15 @@
43
82
 
44
83
  Zeitwerk is an efficient and thread-safe code loader for Ruby.
45
84
 
46
- Given a [conventional file structure](#file-structure), Zeitwerk is able to load your project's classes and modules on demand (autoloading), or upfront (eager loading). You don't need to write `require` calls for your own files, rather, you can streamline your programming knowing that your classes and modules are available everywhere. This feature is efficient, thread-safe, and matches Ruby's semantics for constants.
85
+ Given a [conventional file structure](#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.
86
+
87
+ 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.
47
88
 
48
- Zeitwerk is also able to reload code, which may be handy while developing web applications. Coordination is needed to reload in a thread-safe manner. The documentation below explains how to do this.
89
+ 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.
49
90
 
50
- The gem is designed so that any project, gem dependency, application, etc. can have their own independent loader, coexisting in the same process, managing their own project trees, and independent of each other. Each loader has its own configuration, inflector, and optional logger.
91
+ 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`.
51
92
 
52
- Internally, Zeitwerk issues `require` calls exclusively using absolute file names, so there are no costly file system lookups in `$LOAD_PATH`. Technically, the directories managed by Zeitwerk do not even need to be in `$LOAD_PATH`. Furthermore, Zeitwerk does only one single scan of the project tree, and it descends into subdirectories lazily, only if their namespaces are used.
93
+ Furthermore, Zeitwerk performs a single scan of the project tree at most, lazily descending into subdirectories only when their namespaces are used.
53
94
 
54
95
  <a id="markdown-synopsis" name="synopsis"></a>
55
96
  ## Synopsis
@@ -59,7 +100,7 @@ Main interface for gems:
59
100
  ```ruby
60
101
  # lib/my_gem.rb (main file)
61
102
 
62
- require "zeitwerk"
103
+ require 'zeitwerk'
63
104
  loader = Zeitwerk::Loader.for_gem
64
105
  loader.setup # ready!
65
106
 
@@ -106,7 +147,10 @@ Zeitwerk::Loader.eager_load_all
106
147
  <a id="markdown-file-structure" name="file-structure"></a>
107
148
  ## File structure
108
149
 
109
- To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
150
+ <a id="markdown-the-idea-file-paths-match-constant-paths" name="the-idea-file-paths-match-constant-paths"></a>
151
+ ### The idea: File paths match constant paths
152
+
153
+ For Zeitwerk to work with your file structure, simply name files and directories after the classes and modules they define:
110
154
 
111
155
  ```
112
156
  lib/my_gem.rb -> MyGem
@@ -115,44 +159,130 @@ lib/my_gem/bar_baz.rb -> MyGem::BarBaz
115
159
  lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
116
160
  ```
117
161
 
118
- Every directory configured with `push_dir` acts as root namespace. There can be several of them. For example, given
162
+ You can fine-tune this behavior by [collapsing directories](#collapsing-directories) or [ignoring specific parts of the project](#ignoring-parts-of-the-project), but that is the main idea.
163
+
164
+ <a id="markdown-inner-simple-constants" name="inner-simple-constants"></a>
165
+ ### Inner simple constants
166
+
167
+ While a simple constant like `HttpCrawler::MAX_RETRIES` can be defined in its own file:
119
168
 
120
169
  ```ruby
121
- loader.push_dir(Rails.root.join("app/models"))
122
- loader.push_dir(Rails.root.join("app/controllers"))
170
+ # http_crawler/max_retries.rb
171
+ HttpCrawler::MAX_RETRIES = 10
123
172
  ```
124
173
 
125
- Zeitwerk understands that their respective files and subdirectories belong to the root namespace:
174
+ that is not required, you can also define it the regular way:
126
175
 
176
+ ```ruby
177
+ # http_crawler.rb
178
+ class HttpCrawler
179
+ MAX_RETRIES = 10
180
+ end
127
181
  ```
128
- app/models/user.rb -> User
129
- app/controllers/admin/users_controller.rb -> Admin::UsersController
182
+
183
+ The first example needs a custom [inflection](#inflection) rule:
184
+
185
+ ```ruby
186
+ loader.inflector.inflect('max_retries' => 'MAX_RETRIES')
187
+ ```
188
+
189
+ Otherwise, Zeitwerk would expect the file to define `MaxRetries`.
190
+
191
+ In the second example, no custom rule is needed.
192
+
193
+ <a id="markdown-root-directories-and-root-namespaces" name="root-directories-and-root-namespaces"></a>
194
+ ### Root directories and root namespaces
195
+
196
+ Every directory configured with `push_dir` is called a _root directory_, and they represent _root namespaces_.
197
+
198
+ <a id="markdown-the-default-root-namespace-is-object" name="the-default-root-namespace-is-object"></a>
199
+ #### The default root namespace is `Object`
200
+
201
+ By default, the namespace associated to a root directory is the top-level one: `Object`.
202
+
203
+ For example, given
204
+
205
+ ```ruby
206
+ loader.push_dir("#{__dir__}/models")
207
+ loader.push_dir("#{__dir__}/serializers")
208
+ ```
209
+
210
+ these are the expected classes and modules being defined by these files:
211
+
212
+ ```
213
+ models/user.rb -> User
214
+ serializers/user_serializer.rb -> UserSerializer
215
+ ```
216
+
217
+ <a id="markdown-custom-root-namespaces" name="custom-root-namespaces"></a>
218
+ #### Custom root namespaces
219
+
220
+ 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.
221
+
222
+ For example, given:
223
+
224
+ ```ruby
225
+ require 'active_job'
226
+ require 'active_job/queue_adapters'
227
+ loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters)
130
228
  ```
131
229
 
230
+ a file defining `ActiveJob::QueueAdapters::MyQueueAdapter` does not need the conventional parent directories, you can (and have to) store the file directly below `adapters`:
231
+
232
+ ```
233
+ adapters/my_queue_adapter.rb -> ActiveJob::QueueAdapters::MyQueueAdapter
234
+ ```
235
+
236
+ 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.
237
+
238
+ <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
239
+ #### Nested root directories
240
+
241
+ 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.
242
+
243
+ 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:
244
+
245
+ ```
246
+ app/models/concerns/geolocatable.rb
247
+ ```
248
+
249
+ should define `Geolocatable`, not `Concerns::Geolocatable`.
250
+
132
251
  <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
133
252
  ### Implicit namespaces
134
253
 
135
- Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
254
+ 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.
255
+
256
+ For instance, suppose a project includes an `admin` directory:
136
257
 
137
258
  ```
138
259
  app/controllers/admin/users_controller.rb -> Admin::UsersController
139
260
  ```
140
261
 
141
- `Admin` is autovivified as a module on demand, you do not need to define an `Admin` class or module in an `admin.rb` file explicitly.
262
+ and does not have a file called `admin.rb`, Zeitwerk automatically creates an `Admin` module on your behalf the first time `Admin` is used.
263
+
264
+ 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.
142
265
 
143
266
  <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
144
267
  ### Explicit namespaces
145
268
 
146
- Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
269
+ Classes and modules that act as namespaces can also be explicitly defined in a file. This can be done with ordinary files named after the corresponding constant path, or with special namespace files, or _nsfiles_ for short.
270
+
271
+ <a id="markdown-explicit-namespaces-defined-in-ordinary-files" name="explicit-namespaces-defined-in-ordinary-files"></a>
272
+ #### Explicit namespaces defined in ordinary files
273
+
274
+ Let's consider:
147
275
 
148
276
  ```
149
277
  app/models/hotel.rb -> Hotel
150
278
  app/models/hotel/pricing.rb -> Hotel::Pricing
151
279
  ```
152
280
 
153
- There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
281
+ Since there is a file `app/models/hotel.rb` and also a directory `app/models/hotel`, Zeitwerk realizes `Hotel` is a namespace that is defined in `app/models/hotel.rb`.
282
+
283
+ In order to realize this, the directory or directories conforming the namespace do not need to be next to the file, as in the example, they could be in some other root directory.
154
284
 
155
- The classes and modules from the namespace are already available in the body of the class or module defining it:
285
+ The classes and modules from an explicit namespace are already available in the body of the class or module that defines it:
156
286
 
157
287
  ```ruby
158
288
  class Hotel < ApplicationRecord
@@ -161,20 +291,93 @@ class Hotel < ApplicationRecord
161
291
  end
162
292
  ```
163
293
 
164
- 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.
294
+ When autoloaded, Zeitwerk verifies the expected constant (`Hotel` in the example) stores a class or module object. If it doesn't, `Zeitwerk::Error` is raised.
165
295
 
166
- <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
167
- ### Nested root directories
296
+ <a id="markdown-explicit-namespaces-defined-in-nsfiles" name="explicit-namespaces-defined-in-nsfiles"></a>
297
+ #### Explicit namespaces defined in nsfiles
298
+
299
+ If the loader has an nsfile configured (defaults to `nil`):
168
300
 
169
- Root directories should not be ideally nested, but Zeitwerk supports them because in Rails, for example, both `app/models` and `app/models/concerns` belong to the autoload paths.
301
+ ```ruby
302
+ loader.nsfile = 'ns.rb' # must be set before setup
303
+ ```
170
304
 
171
- Zeitwerk detects nested root directories, and treats them as roots only. In the example above, `concerns` is not considered to be a namespace below `app/models`. For example, the file:
305
+ you can alternatively define the explicit namespace inside its directory:
172
306
 
173
307
  ```
174
- app/models/concerns/geolocatable.rb
308
+ my_component/ns.rb -> MyComponent
309
+ my_component/widget.rb -> MyComponent::Widget
175
310
  ```
176
311
 
177
- should define `Geolocatable`, not `Concerns::Geolocatable`.
312
+ This may be handy for self-contained units for which a `my_component.rb` file in the parent directory would feel unnatural.
313
+
314
+ A loader's nsfile has to be a non-hidden basename with a `.rb` extension, as in the example above. Nsfiles are not inflected, so as long as those conditions hold, they may contain leading underscores, hyphens, etc.
315
+
316
+ Collapsed directories work as expected. For example, if we assume that `src` is collapsed, and that `assets` and `tests` are ignored, you could have the code organized this way:
317
+
318
+ ```
319
+ my_component/src/ns.rb -> MyComponent
320
+ my_component/src/widget.rb -> MyComponent::Widget
321
+ my_component/assets/widget.js
322
+ my_component/tests/test_widget.rb
323
+ ```
324
+
325
+ Loaders with an nsfile configured also support explicit namespaces defined in ordinary files. The conventions are not exclusive project-wide. Some parts may be component-oriented, while in other parts ordinary files may feel more natural. That works.
326
+
327
+ However, attempting to define the same namespace using an ordinary file and an nsfile is an error condition that raises `Zeitwerk::ConflictingNamespaceDefinitionError`.
328
+
329
+ Nsfiles in root directories raise `Zeitwerk::ConflictingNamespaceDefinitionError` too, since the namespace in a root directory is externally defined.
330
+
331
+ Non-ignored files whose basename is equal to the nsfile are always considered to be nsfiles. You cannot opt out. Therefore, if we have:
332
+
333
+ ```ruby
334
+ loader.nsfile = 'index.rb'
335
+ ```
336
+
337
+ there is no way `foo/index.rb` can define `Foo::Index` in any part of the project, it must define `Foo`.
338
+
339
+ <a id="markdown-collapsing-directories" name="collapsing-directories"></a>
340
+ ### Collapsing directories
341
+
342
+ 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:
343
+
344
+ ```
345
+ booking.rb -> Booking
346
+ booking/actions/create.rb -> Booking::Create
347
+ ```
348
+
349
+ To make it work that way, configure Zeitwerk to collapse said directory:
350
+
351
+ ```ruby
352
+ loader.collapse("#{__dir__}/booking/actions")
353
+ ```
354
+
355
+ This method accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
356
+
357
+ You can pass directories and glob patterns. Glob patterns are expanded when they are added, and again on each reload.
358
+
359
+ To illustrate usage of glob patterns, if `actions` in the example above is part of a standardized structure, you could use a wildcard:
360
+
361
+ ```ruby
362
+ loader.collapse("#{__dir__}/*/actions")
363
+ ```
364
+
365
+ <a id="markdown-testing-compliance" name="testing-compliance"></a>
366
+ ### Testing compliance
367
+
368
+ When a managed file is loaded, Zeitwerk verifies the expected constant is defined. If it is not, `Zeitwerk::NameError` is raised.
369
+
370
+ So, an easy way to ensure compliance in the test suite is to eager load the project:
371
+
372
+ ```ruby
373
+ begin
374
+ loader.eager_load(force: true)
375
+ rescue Zeitwerk::NameError => e
376
+ flunk e.message
377
+ else
378
+ assert true
379
+ end
380
+ ```
178
381
 
179
382
  <a id="markdown-usage" name="usage"></a>
180
383
  ## Usage
@@ -182,6 +385,9 @@ should define `Geolocatable`, not `Concerns::Geolocatable`.
182
385
  <a id="markdown-setup" name="setup"></a>
183
386
  ### Setup
184
387
 
388
+ <a id="markdown-generic" name="generic"></a>
389
+ #### Generic
390
+
185
391
  Loaders are ready to load code right after calling `setup` on them:
186
392
 
187
393
  ```ruby
@@ -198,14 +404,37 @@ loader.push_dir(...)
198
404
  loader.setup
199
405
  ```
200
406
 
201
- The loader returned by `Zeitwerk::Loader.for_gem` has the directory of the caller pushed, normally that is the absolute path of `lib`. In that sense, `for_gem` can be used also by projects with a gem structure, even if they are not technically gems. That is, you don't need a gemspec or anything.
407
+ <a id="markdown-for_gem" name="for_gem"></a>
408
+ #### for_gem
202
409
 
203
- If the main module of a library 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:
410
+ `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:
411
+
412
+ ```
413
+ lib/my_gem.rb # MyGem
414
+ lib/my_gem/version.rb # MyGem::VERSION
415
+ lib/my_gem/foo.rb # MyGem::Foo
416
+ ```
417
+
418
+ Neither a gemspec nor a version file are technically required, this helper works as long as the code is organized using that standard structure.
419
+
420
+ Conceptually, `for_gem` translates to:
421
+
422
+ ```ruby
423
+ # lib/my_gem.rb
424
+
425
+ require 'zeitwerk'
426
+ loader = Zeitwerk::Loader.new
427
+ loader.tag = File.basename(__FILE__, '.rb')
428
+ loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
429
+ loader.push_dir(File.dirname(__FILE__))
430
+ ```
431
+
432
+ 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:
204
433
 
205
434
  ```ruby
206
435
  # lib/my_gem.rb (main file)
207
436
 
208
- require "zeitwerk"
437
+ require 'zeitwerk'
209
438
  loader = Zeitwerk::Loader.for_gem
210
439
  loader.setup
211
440
 
@@ -216,35 +445,109 @@ module MyGem
216
445
  end
217
446
  ```
218
447
 
219
- Zeitwerk works internally only with absolute paths to avoid costly file searches in `$LOAD_PATH`. Indeed, the root directories do not even need to belong to `$LOAD_PATH`, everything just works by design if they don't.
448
+ 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.
220
449
 
221
- <a id="markdown-reloading" name="reloading"></a>
222
- ### Reloading
450
+ `Zeitwerk::Loader.for_gem` is idempotent when invoked from the same file, to support gems that want to reload (unlikely).
223
451
 
224
- Zeitwerk is able to reload code, but you need to enable this feature:
452
+ If the entry point of your gem lives in a subdirectory of `lib` because it is reopening a namespace defined somewhere else, please use the generic API to setup the loader, and make sure you check the section [_Reopening third-party namespaces_](#reopening-third-party-namespaces) down below.
453
+
454
+ Loaders returned by `Zeitwerk::Loader.for_gem` issue warnings if `lib` has extra Ruby files or directories.
455
+
456
+ 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.
457
+
458
+ If the warning is legit, just tell the loader to ignore the offending file or directory:
225
459
 
226
460
  ```ruby
227
- loader = Zeitwerk::Loader.new
228
- loader.push_dir(...)
229
- loader.enable_reloading # you need to opt-in before setup
461
+ loader.ignore("#{__dir__}/generators")
462
+ ```
463
+
464
+ Otherwise, there's a flag to say the extra stuff is OK:
465
+
466
+ ```ruby
467
+ Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
468
+ ```
469
+
470
+ <a id="markdown-for_gem_extension" name="for_gem_extension"></a>
471
+ #### for_gem_extension
472
+
473
+ Let's suppose you are writing a gem to extend `Net::HTTP` with some niche feature. By [convention](https://guides.rubygems.org/name-your-gem/):
474
+
475
+ * The gem should be called `net-http-niche_feature`. That is, hyphens for the extended part, a hyphen, and underscores for yours.
476
+ * The namespace should be `Net::HTTP::NicheFeature`.
477
+ * The entry point should be `lib/net/http/niche_feature.rb`.
478
+ * 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.
479
+
480
+ The top-level file mentioned in the last point is optional. In particular, from
481
+
482
+ ```ruby
483
+ gem 'net-http-niche_feature'
484
+ ```
485
+
486
+ if the hyphenated file does not exist, Bundler notes the conventional hyphenated pattern and issues a `require` for `net/http/niche_feature`.
487
+
488
+ Gem extensions following the conventions above have a dedicated loader constructor: `Zeitwerk::Loader.for_gem_extension`.
489
+
490
+ The structure of the gem would be like this:
491
+
492
+ ```ruby
493
+ # lib/net-http-niche_feature.rb (optional)
494
+
495
+ # For technical reasons, this cannot be require_relative.
496
+ require 'net/http/niche_feature'
497
+
498
+
499
+ # lib/net/http/niche_feature.rb
500
+
501
+ require 'net/http'
502
+ require 'zeitwerk'
503
+
504
+ loader = Zeitwerk::Loader.for_gem_extension(Net::HTTP)
230
505
  loader.setup
231
- ...
232
- loader.reload
506
+
507
+ module Net::HTTP::NicheFeature
508
+ # Since the setup has been performed, at this point we are already able
509
+ # to reference project constants, in this case Net::HTTP::NicheFeature::MyMixin.
510
+ include MyMixin
511
+ end
512
+
513
+
514
+ # lib/net/http/niche_feature/version.rb
515
+
516
+ module Net::HTTP::NicheFeature
517
+ VERSION = '1.0.0'
518
+ end
233
519
  ```
234
520
 
235
- There is no way to undo this, either you want to reload or you don't.
521
+ `Zeitwerk::Loader.for_gem_extension` expects as argument the namespace being extended, which has to be a non-anonymous class or module object.
236
522
 
237
- Enabling reloading after setup raises `Zeitwerk::Error`. Similarly, calling `reload` without having enabled reloading also raises `Zeitwerk::Error`.
523
+ If it exists, `lib/net/http/niche_feature/version.rb` is expected to define `Net::HTTP::NicheFeature::VERSION`.
238
524
 
239
- 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.
525
+ 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.
240
526
 
241
- Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
527
+ `Zeitwerk::Loader.for_gem_extension` is idempotent when invoked from the same file, to support gems that want to reload (unlikely).
242
528
 
243
- It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
529
+ <a id="markdown-autoloading" name="autoloading"></a>
530
+ ### Autoloading
531
+
532
+ 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.
533
+
534
+ Let's revisit the example above:
535
+
536
+ ```ruby
537
+ # lib/my_gem.rb (main file)
538
+
539
+ require 'zeitwerk'
540
+ loader = Zeitwerk::Loader.for_gem
541
+ loader.setup
542
+
543
+ module MyGem
544
+ include MyLogger # (*)
545
+ end
546
+ ```
244
547
 
245
- In order for reloading to be thread-safe, you need to implement some coordination. For example, a web framework that serves each request with its own thread may have a globally accessible RW lock. When a request comes in, the framework acquires the lock for reading at the beginning, and the code in the framework that calls `loader.reload` needs to acquire the lock for writing.
548
+ That works, and there is no `require 'my_gem/my_logger'`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
246
549
 
247
- 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 controller class objects or instances in internal structures, on reload it has to refresh them somehow, possibly reevaluating routes.
550
+ If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
248
551
 
249
552
  <a id="markdown-eager-loading" name="eager-loading"></a>
250
553
  ### Eager loading
@@ -255,7 +558,18 @@ Zeitwerk instances are able to eager load their managed files:
255
558
  loader.eager_load
256
559
  ```
257
560
 
258
- That skips [ignored files and directories](#ignoring-parts-of-the-project), and you can also tell Zeitwerk that certain files or directories are autoloadable, but should not be eager loaded:
561
+ That skips [ignored files and directories](#ignoring-parts-of-the-project).
562
+
563
+ In gems, the method needs to be invoked after the main namespace has been defined, as shown in [Synopsis](#synopsis).
564
+
565
+ Eager loading is synchronized and idempotent.
566
+
567
+ Attempting to eager load without previously calling `setup` raises `Zeitwerk::SetupRequired`.
568
+
569
+ <a id="markdown-eager-load-exclusions" name="eager-load-exclusions"></a>
570
+ #### Eager load exclusions
571
+
572
+ You can tell Zeitwerk that certain files or directories are autoloadable, but should not be eager loaded:
259
573
 
260
574
  ```ruby
261
575
  db_adapters = "#{__dir__}/my_gem/db_adapters"
@@ -264,11 +578,95 @@ loader.setup
264
578
  loader.eager_load # won't eager load the database adapters
265
579
  ```
266
580
 
267
- In gems, the method needs to be invoked after the main namespace has been defined, as shown in [Synopsis](https://github.com/fxn/zeitwerk#synopsis).
581
+ However, that can be overridden with `force`:
268
582
 
269
- Eager loading is synchronized and idempotent.
583
+ ```ruby
584
+ loader.eager_load(force: true) # database adapters are eager loaded
585
+ ```
586
+
587
+ Which may be handy if the project eager loads in the test suite to [ensure project layout compliance](#testing-compliance).
588
+
589
+ The `force` flag does not affect ignored files and directories, those are still ignored.
590
+
591
+ <a id="markdown-eager-load-directories" name="eager-load-directories"></a>
592
+ #### Eager load directories
593
+
594
+ The method `Zeitwerk::Loader#eager_load_dir` eager loads a given directory, recursively:
595
+
596
+ ```ruby
597
+ loader.eager_load_dir("#{__dir__}/custom_web_app/routes")
598
+ ```
599
+
600
+ 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.
601
+
602
+ 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`.
603
+
604
+ [Eager load exclusions](#eager-load-exclusions), [ignored files and directories](#ignoring-parts-of-the-project), and [shadowed files](#shadowed-files) are not eager loaded.
605
+
606
+ `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.
607
+
608
+ The method checks if a regular eager load was already executed, in which case it returns fast.
609
+
610
+ Nested root directories which are descendants of the argument are skipped. Those subtrees are considered to be conceptually apart.
611
+
612
+ Attempting to eager load a directory without previously calling `setup` raises `Zeitwerk::SetupRequired`.
613
+
614
+ <a id="markdown-eager-load-namespaces" name="eager-load-namespaces"></a>
615
+ #### Eager load namespaces
616
+
617
+ The method `Zeitwerk::Loader#eager_load_namespace` eager loads a given namespace, recursively:
270
618
 
271
- If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
619
+ ```ruby
620
+ loader.eager_load_namespace(MyApp::Routes)
621
+ ```
622
+
623
+ 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.
624
+
625
+ The argument has to be a class or module object and the method raises `Zeitwerk::Error` otherwise.
626
+
627
+ 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
628
+
629
+ ```
630
+ root_dir1/my_app/routes
631
+ root_dir2/my_app/routes
632
+ root_dir3/my_app/routes
633
+ ```
634
+
635
+ where `root_dir{1,2,3}` are root directories, eager loading `MyApp::Routes` will eager load the contents of the three corresponding directories.
636
+
637
+ There might exist external source trees implementing part of the namespace. This happens routinely, because top-level constants are stored in the globally shared `Object`. It happens also when deliberately [reopening third-party namespaces](#reopening-third-party-namespaces). Such external code is not eager loaded, the implementation is carefully scoped to what the receiver manages to avoid side-effects elsewhere.
638
+
639
+ 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.
640
+
641
+ [Eager load exclusions](#eager-load-exclusions), [ignored files and directories](#ignoring-parts-of-the-project), and [shadowed files](#shadowed-files) are not eager loaded.
642
+
643
+ `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.
644
+
645
+ The method checks if a regular eager load was already executed, in which case it returns fast.
646
+
647
+ 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.
648
+
649
+ Attempting to eager load a namespace without previously calling `setup` raises `Zeitwerk::SetupRequired`.
650
+
651
+ <a id="markdown-eager-load-namespaces-shared-by-several-loaders" name="eager-load-namespaces-shared-by-several-loaders"></a>
652
+ #### Eager load namespaces shared by several loaders
653
+
654
+ The method `Zeitwerk::Loader.eager_load_namespace` broadcasts `eager_load_namespace` to all loaders.
655
+
656
+ ```ruby
657
+ Zeitwerk::Loader.eager_load_namespace(MyFramework::Routes)
658
+ ```
659
+
660
+ 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.
661
+
662
+ 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.
663
+
664
+ 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.
665
+
666
+ <a id="markdown-global-eager-load" name="global-eager-load"></a>
667
+ #### Global eager load
668
+
669
+ If you want to eager load yourself and all dependencies that use Zeitwerk, you can broadcast the `eager_load` call to all instances:
272
670
 
273
671
  ```ruby
274
672
  Zeitwerk::Loader.eager_load_all
@@ -278,14 +676,95 @@ This may be handy in top-level services, like web applications.
278
676
 
279
677
  Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
280
678
 
679
+ 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.
680
+
681
+ 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.
682
+
683
+ <a id="markdown-loading-individual-files" name="loading-individual-files"></a>
684
+ ### Loading individual files
685
+
686
+ The method `Zeitwerk::Loader#load_file` loads an individual Ruby file:
687
+
688
+ ```ruby
689
+ loader.load_file("#{__dir__}/custom_web_app/routes.rb")
690
+ ```
691
+
692
+ 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.
693
+
694
+ Both strings and `Pathname` objects are supported as arguments. The method raises `Zeitwerk::Error` if the argument is not a Ruby file, is [ignored](#ignoring-parts-of-the-project), is [shadowed](#shadowed-files), or is not managed by the receiver.
695
+
696
+ `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.
697
+
698
+ 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.
699
+
700
+ <a id="markdown-reloading" name="reloading"></a>
701
+ ### Reloading
702
+
703
+ <a id="markdown-configuration-and-usage" name="configuration-and-usage"></a>
704
+ #### Configuration and usage
705
+
706
+ Zeitwerk is able to reload code, but you need to enable this feature:
707
+
708
+ ```ruby
709
+ loader = Zeitwerk::Loader.new
710
+ loader.push_dir(...)
711
+ loader.enable_reloading # you need to opt-in before setup
712
+ loader.setup
713
+ ...
714
+ loader.reload
715
+ ```
716
+
717
+ There is no way to undo this, either you want to reload or you don't.
718
+
719
+ 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`.
720
+
721
+ 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.
722
+
723
+ Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
724
+
725
+ It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
726
+
727
+ <a id="markdown-thread-safety" name="thread-safety"></a>
728
+ #### Thread-safety
729
+
730
+ In order to reload safely, no other thread can be autoloading or reloading concurrently. Client code is responsible for this coordination.
731
+
732
+ 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:
733
+
734
+ ```ruby
735
+ require 'concurrent/atomic/read_write_lock'
736
+
737
+ MyFramework::RELOAD_RW_LOCK = Concurrent::ReadWriteLock.new
738
+ ```
739
+
740
+ You acquire the lock for reading for serving each individual request:
741
+
742
+ ```ruby
743
+ MyFramework::RELOAD_RW_LOCK.with_read_lock do
744
+ serve(request)
745
+ end
746
+ ```
747
+
748
+ Then, when a reload is triggered, just acquire the lock for writing in order to execute the method call safely:
749
+
750
+ ```ruby
751
+ MyFramework::RELOAD_RW_LOCK.with_write_lock do
752
+ loader.reload
753
+ end
754
+ ```
755
+
756
+ 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.
757
+
281
758
  <a id="markdown-inflection" name="inflection"></a>
282
759
  ### Inflection
283
760
 
284
- 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.
761
+ 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.
285
762
 
286
763
  <a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
287
764
  #### Zeitwerk::Inflector
288
765
 
766
+ Each loader instantiated with `Zeitwerk::Loader.new` has an inflector of this type by default.
767
+
289
768
  This is a very basic inflector that converts snake case to camel case:
290
769
 
291
770
  ```
@@ -298,30 +777,80 @@ The camelize logic can be overridden easily for individual basenames:
298
777
 
299
778
  ```ruby
300
779
  loader.inflector.inflect(
301
- "html_parser" => "HTMLParser",
302
- "mysql_adapter" => "MySQLAdapter"
780
+ 'html_parser' => 'HTMLParser',
781
+ 'mysql_adapter' => 'MySQLAdapter'
303
782
  )
304
783
  ```
305
784
 
306
785
  The `inflect` method can be invoked several times if you prefer this other style:
307
786
 
308
787
  ```ruby
309
- loader.inflector.inflect "html_parser" => "HTMLParser"
310
- loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
788
+ loader.inflector.inflect 'html_parser' => 'HTMLParser'
789
+ loader.inflector.inflect 'mysql_adapter' => 'MySQLAdapter'
311
790
  ```
312
791
 
313
- Overrides need to be configured before calling `setup`.
792
+ Overrides have to match exactly directory or file (without extension) _basenames_. For example, if you configure
793
+
794
+ ```ruby
795
+ loader.inflector.inflect('xml' => 'XML')
796
+ ```
797
+
798
+ then the following constants are expected:
799
+
800
+ ```
801
+ xml.rb -> XML
802
+ foo/xml -> Foo::XML
803
+ foo/bar/xml.rb -> Foo::Bar::XML
804
+ ```
805
+
806
+ 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:
807
+
808
+ ```ruby
809
+ loader.inflector.inflect(
810
+ 'xml' => 'XML',
811
+ 'xml_parser' => 'XMLParser'
812
+ )
813
+ ```
814
+
815
+ If you need more flexibility, you can define a custom inflector, as explained down below.
314
816
 
315
- There are no inflection rules or global configuration that can affect this inflector. It is deterministic.
817
+ Overrides need to be configured before calling `setup`.
316
818
 
317
- Loaders instantiated with `Zeitwerk::Loader.new` have an inflector of this type, independent of each other.
819
+ 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.
318
820
 
319
821
  <a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
320
822
  #### Zeitwerk::GemInflector
321
823
 
824
+ Each loader instantiated with `Zeitwerk::Loader.for_gem` has an inflector of this type by default.
825
+
322
826
  This inflector is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
323
827
 
324
- Loaders instantiated with `Zeitwerk::Loader.for_gem` have an inflector of this type, independent of each other.
828
+ 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.
829
+
830
+ <a id="markdown-zeitwerknullinflector" name="zeitwerknullinflector"></a>
831
+ #### Zeitwerk::NullInflector
832
+
833
+ This is an experimental inflector that simply returns its input unchanged.
834
+
835
+ ```ruby
836
+ loader.inflector = Zeitwerk::NullInflector.new
837
+ ```
838
+
839
+ In a project using this inflector, the names of files and directories are equal to the constants they define:
840
+
841
+ ```
842
+ User.rb -> User
843
+ HTMLParser.rb -> HTMLParser
844
+ Admin/Role.rb -> Admin::Role
845
+ ```
846
+
847
+ 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.
848
+
849
+ 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!
850
+
851
+ 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.
852
+
853
+ 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`.
325
854
 
326
855
  <a id="markdown-custom-inflector" name="custom-inflector"></a>
327
856
  #### Custom inflector
@@ -334,7 +863,7 @@ The inflectors that ship with Zeitwerk are deterministic and simple. But you can
334
863
  class MyInflector < Zeitwerk::Inflector
335
864
  def camelize(basename, abspath)
336
865
  if basename =~ /\Ahtml_(.*)/
337
- "HTML" + super($1, abspath)
866
+ 'HTML' + super($1, abspath)
338
867
  else
339
868
  super
340
869
  end
@@ -365,8 +894,8 @@ module MyGem
365
894
  end
366
895
 
367
896
  # lib/my_gem.rb
368
- require "zeitwerk"
369
- require_relative "my_gem/inflector"
897
+ require 'zeitwerk'
898
+ require_relative 'my_gem/inflector'
370
899
 
371
900
  loader = Zeitwerk::Loader.for_gem
372
901
  loader.inflector = MyGem::Inflector.new(__FILE__)
@@ -397,6 +926,129 @@ class MyGem::Inflector < Zeitwerk::GemInflector
397
926
  end
398
927
  ```
399
928
 
929
+ <a id="markdown-callbacks" name="callbacks"></a>
930
+ ### Callbacks
931
+
932
+ <a id="markdown-the-on_setup-callback" name="the-on_setup-callback"></a>
933
+ #### The on_setup callback
934
+
935
+ The `on_setup` callback is fired on setup and on each reload:
936
+
937
+ ```ruby
938
+ loader.on_setup do
939
+ # Ready to autoload here.
940
+ end
941
+ ```
942
+
943
+ Multiple `on_setup` callbacks are supported, and they run in order of definition.
944
+
945
+ If `setup` was already executed, the callback is fired immediately.
946
+
947
+ <a id="markdown-the-on_load-callback" name="the-on_load-callback"></a>
948
+ #### The on_load callback
949
+
950
+ 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.
951
+
952
+ For example, let's imagine this class belongs to a Rails application:
953
+
954
+ ```ruby
955
+ class SomeApiClient
956
+ class << self
957
+ attr_accessor :endpoint
958
+ end
959
+ end
960
+ ```
961
+
962
+ With `on_load`, it is easy to schedule code at boot time that initializes `endpoint` according to the configuration:
963
+
964
+ ```ruby
965
+ # config/environments/development.rb
966
+ loader.on_load('SomeApiClient') do |klass, _abspath|
967
+ klass.endpoint = 'https://api.dev'
968
+ end
969
+
970
+ # config/environments/production.rb
971
+ loader.on_load('SomeApiClient') do |klass, _abspath|
972
+ klass.endpoint = 'https://api.prod'
973
+ end
974
+ ```
975
+
976
+ Some uses cases:
977
+
978
+ * 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.
979
+ * Delaying the execution of the block until the class is loaded for performance.
980
+ * 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.
981
+
982
+ `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.
983
+
984
+ Multiple callbacks on the same target are supported, and they run in order of definition.
985
+
986
+ 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`.
987
+
988
+ Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
989
+
990
+ It is also possible to be called when any constant managed by the loader is loaded:
991
+
992
+ ```ruby
993
+ loader.on_load do |cpath, value, abspath|
994
+ # ...
995
+ end
996
+ ```
997
+
998
+ 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.
999
+
1000
+ Multiple callbacks like these are supported, and they run in order of definition.
1001
+
1002
+ 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.
1003
+
1004
+ If both types of callbacks are defined, the specific ones run first.
1005
+
1006
+ Since `on_load` callbacks are executed right after files are loaded, even if the loading context seems to be far away, in practice **the block is subject to [circular dependencies](#beware-of-circular-dependencies)**. As a rule of thumb, as far as loading order and its interdependencies is concerned, you have to program as if the block was executed at the bottom of the file just loaded.
1007
+
1008
+ <a id="markdown-the-on_unload-callback" name="the-on_unload-callback"></a>
1009
+ #### The on_unload callback
1010
+
1011
+ 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.
1012
+
1013
+ 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:
1014
+
1015
+ ```ruby
1016
+ loader.on_unload('Country') do |klass, _abspath|
1017
+ klass.clear_cache
1018
+ end
1019
+ ```
1020
+
1021
+ `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.
1022
+
1023
+ `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.
1024
+
1025
+ Multiple callbacks on the same target are supported, and they run in order of definition.
1026
+
1027
+ Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
1028
+
1029
+ It is also possible to be called when any constant managed by the loader is unloaded:
1030
+
1031
+ ```ruby
1032
+ loader.on_unload do |cpath, value, abspath|
1033
+ # ...
1034
+ end
1035
+ ```
1036
+
1037
+ 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.
1038
+
1039
+ Multiple callbacks like these are supported, and they run in order of definition.
1040
+
1041
+ If both types of callbacks are defined, the specific ones run first.
1042
+
1043
+ <a id="markdown-technical-details" name="technical-details"></a>
1044
+ #### Technical details
1045
+
1046
+ 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?
1047
+
1048
+ 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.
1049
+
1050
+ 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.
1051
+
400
1052
  <a id="markdown-logging" name="logging"></a>
401
1053
  ### Logging
402
1054
 
@@ -432,7 +1084,7 @@ Zeitwerk::Loader.default_logger = method(:puts)
432
1084
 
433
1085
  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.
434
1086
 
435
- As a curiosity, if your project has namespaces you'll notice in the traces Zeitwerk sets autoloads for _directories_. That's a technique used to be able to descend into subdirectories on demand, avoiding that way unnecessary tree walks.
1087
+ 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.
436
1088
 
437
1089
  <a id="markdown-loader-tag" name="loader-tag"></a>
438
1090
  #### Loader tag
@@ -446,7 +1098,7 @@ Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
446
1098
  By default, a random tag like the one above is assigned, but you can change it:
447
1099
 
448
1100
  ```
449
- loader.tag = "grep_me"
1101
+ loader.tag = 'grep_me'
450
1102
  ```
451
1103
 
452
1104
  The tag of a loader returned by `for_gem` is the basename of the root file without extension:
@@ -458,12 +1110,14 @@ Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
458
1110
  <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
459
1111
  ### Ignoring parts of the project
460
1112
 
461
- Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
1113
+ Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have the extension ".rb".
462
1114
 
463
1115
  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.
464
1116
 
465
1117
  You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
466
1118
 
1119
+ 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.
1120
+
467
1121
  Let's see some use cases.
468
1122
 
469
1123
  <a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
@@ -479,7 +1133,9 @@ Kernel.module_eval do
479
1133
  end
480
1134
  ```
481
1135
 
482
- That file does not define a constant path after the path name and you need to tell Zeitwerk:
1136
+ `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.
1137
+
1138
+ The extension can still coexist with the rest of the project, you only need to tell Zeitwerk to ignore it:
483
1139
 
484
1140
  ```ruby
485
1141
  kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
@@ -495,6 +1151,14 @@ loader.ignore(core_ext)
495
1151
  loader.setup
496
1152
  ```
497
1153
 
1154
+ Now, that file has to be loaded manually with `require` or `require_relative`:
1155
+
1156
+ ```ruby
1157
+ require_relative 'my_gem/core_ext/kernel'
1158
+ ```
1159
+
1160
+ and you can do that anytime, before configuring the loader, or after configuring the loader, does not matter.
1161
+
498
1162
  <a id="markdown-use-case-the-adapter-pattern" name="use-case-the-adapter-pattern"></a>
499
1163
  #### Use case: The adapter pattern
500
1164
 
@@ -504,7 +1168,7 @@ Let's imagine your project talks to databases, supports several, and has adapter
504
1168
 
505
1169
  ```ruby
506
1170
  # my_gem/db_adapters/postgresql.rb
507
- require "pg"
1171
+ require 'pg'
508
1172
  ```
509
1173
 
510
1174
  but you don't want your users to install them all, only the one they are going to use.
@@ -536,34 +1200,233 @@ loader.ignore(tests)
536
1200
  loader.setup
537
1201
  ```
538
1202
 
539
- <a id="markdown-edge-cases" name="edge-cases"></a>
540
- ### Edge cases
1203
+ <a id="markdown-shadowed-files" name="shadowed-files"></a>
1204
+ ### Shadowed files
1205
+
1206
+ In Ruby, if you have several files called `foo.rb` in different directories of `$LOAD_PATH` and execute
1207
+
1208
+ ```ruby
1209
+ require 'foo'
1210
+ ```
1211
+
1212
+ the first one found gets loaded, and the rest are ignored.
1213
+
1214
+ 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
1215
+
1216
+ ```
1217
+ file #{file} is ignored because #{previous_occurrence} has precedence
1218
+ ```
1219
+
1220
+ (This message is not public interface and may change, you cannot rely on that exact wording.)
1221
+
1222
+ 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
1223
+
1224
+ ```
1225
+ file #{file} is ignored because #{constant_path} is already defined
1226
+ ```
1227
+
1228
+ (This message is not public interface and may change, you cannot rely on that exact wording.)
1229
+
1230
+ Shadowing only applies to Ruby files, namespace definition can be spread over multiple directories. And you can also reopen third-party namespaces if done [orderly](#reopening-third-party-namespaces).
541
1231
 
542
- A class or module that acts as a namespace:
1232
+ <a id="markdown-beware-of-circular-dependencies" name="beware-of-circular-dependencies"></a>
1233
+ ### Beware of circular dependencies
1234
+
1235
+ In Ruby, you can't have certain top-level circular dependencies. Take for example:
543
1236
 
544
1237
  ```ruby
545
- # trip.rb
546
- class Trip
547
- include Geolocation
1238
+ # c.rb
1239
+ class C < D
548
1240
  end
549
1241
 
550
- # trip/geolocation.rb
551
- module Trip::Geolocation
552
- ...
1242
+ # d.rb
1243
+ class D
1244
+ C
1245
+ end
1246
+ ```
1247
+
1248
+ In order to define `C`, you need to load `D`. However, the body of `D` refers to `C`.
1249
+
1250
+ Circular dependencies like those do not work in plain Ruby, and therefore do not work in projects managed by Zeitwerk either.
1251
+
1252
+ <a id="markdown-reopening-third-party-namespaces" name="reopening-third-party-namespaces"></a>
1253
+ ### Reopening third-party namespaces
1254
+
1255
+ Projects managed by Zeitwerk can work with namespaces defined by third-party libraries. However, they have to be loaded in memory before calling `setup`.
1256
+
1257
+ For example, let's imagine you're writing a gem that implements an adapter for [Active Job](https://guides.rubyonrails.org/active_job_basics.html) that uses AwesomeQueue as backend. By convention, your gem has to define a class called `ActiveJob::QueueAdapters::AwesomeQueue`, and it has to do so in a file with a matching path:
1258
+
1259
+ ```ruby
1260
+ # lib/active_job/queue_adapters/awesome_queue.rb
1261
+ module ActiveJob
1262
+ module QueueAdapters
1263
+ class AwesomeQueue
1264
+ # ...
1265
+ end
1266
+ end
1267
+ end
1268
+ ```
1269
+
1270
+ 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.
1271
+
1272
+ Bottom line, Zeitwerk should not be managing those namespaces. Active Job owns them and defines them. Your gem needs to _reopen_ them.
1273
+
1274
+ 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:
1275
+
1276
+ ```ruby
1277
+ # Ensure these namespaces are reopened, not defined.
1278
+ require 'active_job'
1279
+ require 'active_job/queue_adapters'
1280
+
1281
+ require 'zeitwerk'
1282
+ # By passing the flag, we acknowledge the extra directory lib/active_job
1283
+ # has to be managed by the loader and no warning has to be issued for it.
1284
+ loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
1285
+ loader.setup
1286
+ ```
1287
+
1288
+ 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.
1289
+
1290
+ <a id="markdown-introspection" name="introspection"></a>
1291
+ ### Introspection
1292
+
1293
+ <a id="markdown-zeitwerkloaderdirs" name="zeitwerkloaderdirs"></a>
1294
+ #### `Zeitwerk::Loader#dirs`
1295
+
1296
+ The method `Zeitwerk::Loader#dirs` returns an array with the absolute paths of the root directories as strings:
1297
+
1298
+ ```ruby
1299
+ loader = Zeitwerk::Loader.new
1300
+ loader.push_dir(Pathname.new('/foo'))
1301
+ loader.dirs # => ['/foo']
1302
+ ```
1303
+
1304
+ 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:
1305
+
1306
+ ```ruby
1307
+ loader = Zeitwerk::Loader.new
1308
+ loader.push_dir(Pathname.new('/foo'))
1309
+ loader.push_dir(Pathname.new('/bar'), namespace: Bar)
1310
+ loader.dirs(namespaces: true) # => { '/foo' => Object, '/bar' => Bar }
1311
+ ```
1312
+
1313
+ By default, ignored root directories are filtered out. If you want them included, please pass `ignored: true`.
1314
+
1315
+ These collections are read-only. Please add to them with `Zeitwerk::Loader#push_dir`.
1316
+
1317
+ <a id="markdown-autoloaded-constants" name="autoloaded-constants"></a>
1318
+ #### Autoloaded Constants
1319
+
1320
+ Zeitwerk does not keep track of autoloaded constants to minimize its memory footprint, but you can collect them with `on_load` if you will:
1321
+
1322
+ ```ruby
1323
+ autoloaded_cpaths = []
1324
+ loader.on_load do |cpath, _value, _abspath|
1325
+ autoloaded_cpaths << cpath
553
1326
  end
554
1327
  ```
555
1328
 
556
- has to be defined with the `class` or `module` keywords, as in the example above.
1329
+ <a id="markdown-zeitwerkloadercpath_expected_at" name="zeitwerkloadercpath_expected_at"></a>
1330
+ #### `Zeitwerk::Loader#cpath_expected_at`
1331
+
1332
+ Given a path as a string or `Pathname` object, `Zeitwerk::Loader#cpath_expected_at` returns a string with the corresponding expected constant path.
1333
+
1334
+ Some examples, assuming that `app/models` is a root directory:
1335
+
1336
+ ```ruby
1337
+ loader.cpath_expected_at('app/models') # => 'Object'
1338
+ loader.cpath_expected_at('app/models/user.rb') # => 'User'
1339
+ loader.cpath_expected_at('app/models/hotel') # => 'Hotel'
1340
+ loader.cpath_expected_at('app/models/hotel/billing.rb') # => 'Hotel::Billing'
1341
+ ```
1342
+
1343
+ If `collapsed` is a collapsed directory:
1344
+
1345
+ ```ruby
1346
+ loader.cpath_expected_at('a/b/collapsed/c') # => 'A::B::C'
1347
+ loader.cpath_expected_at('a/b/collapsed') # => 'A::B', edge case
1348
+ loader.cpath_expected_at('a/b') # => 'A::B'
1349
+ ```
1350
+
1351
+ If the argument corresponds to an [ignored file or directory](#ignoring-parts-of-the-project), the method returns `nil`. Same if the argument is not managed by the loader.
1352
+
1353
+ `Zeitwerk::Error` is raised if the given path does not exist:
1354
+
1355
+ ```ruby
1356
+ loader.cpath_expected_at('non_existing_file.rb') # => Zeitwerk::Error
1357
+ ```
557
1358
 
558
- For technical reasons, raw constant assignment is not supported:
1359
+ `Zeitwerk::NameError` is raised if a constant path cannot be derived from it:
559
1360
 
560
1361
  ```ruby
561
- # trip.rb
562
- Trip = Class.new { ... } # NOT SUPPORTED
563
- Trip = Struct.new { ... } # NOT SUPPORTED
1362
+ loader.cpath_expected_at('8.rb') # => Zeitwerk::NameError
1363
+ ```
1364
+
1365
+ This method does not parse file contents and does not guarantee files define the returned constant path.
1366
+
1367
+ Similarly, this method does not validate the project tree. If the project has conflicting oridinary and nsfiles for the same namespace, for example, the call will return the expected constant path for each of them without raising.
1368
+
1369
+ `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.
1370
+
1371
+ <a id="markdown-zeitwerkloaderall_expected_cpaths" name="zeitwerkloaderall_expected_cpaths"></a>
1372
+ #### `Zeitwerk::Loader#all_expected_cpaths`
1373
+
1374
+ 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.
1375
+
1376
+ 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.
1377
+
1378
+ For example, if `lib` is the root directory of a gem with the following contents:
1379
+
1380
+ ```
1381
+ lib/.DS_Store
1382
+ lib/my_gem.rb
1383
+ lib/my_gem/version.rb
1384
+ lib/my_gem/drivers/unix.rb
1385
+ lib/my_gem/drivers/windows.rb
1386
+ lib/my_gem/collapsed/foo.rb
1387
+ lib/my_gem/ignored.rb
1388
+ lib/tasks/my_gem.rake
564
1389
  ```
565
1390
 
566
- This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
1391
+ `Zeitwerk::Loader#all_expected_cpaths` would return (maybe in a different order):
1392
+
1393
+ ```ruby
1394
+ {
1395
+ '/.../lib' => 'Object',
1396
+ '/.../lib/my_gem.rb' => 'MyGem',
1397
+ '/.../lib/my_gem' => 'MyGem',
1398
+ '/.../lib/my_gem/version.rb' => 'MyGem::VERSION',
1399
+ '/.../lib/my_gem/drivers' => 'MyGem::Drivers',
1400
+ '/.../lib/my_gem/drivers/unix.rb' => 'MyGem::Drivers::Unix',
1401
+ '/.../lib/my_gem/drivers/windows.rb' => 'MyGem::Drivers::Windows',
1402
+ '/.../lib/my_gem/collapsed' => 'MyGem',
1403
+ '/.../lib/my_gem/collapsed/foo.rb' => 'MyGem::Foo'
1404
+ }
1405
+ ```
1406
+
1407
+ 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).
1408
+
1409
+ The file `lib/.DS_Store` is hidden, hence excluded. The directory `lib/tasks` is also excluded because it contains no files with extension ".rb".
1410
+
1411
+ Directory paths do not have trailing slashes.
1412
+
1413
+ The order of the hash entries is undefined.
1414
+
1415
+ This method does not parse file contents and does not guarantee files define the returned constant path.
1416
+
1417
+ Similarly, this method does not validate the project tree. If the project has conflicting oridinary and nsfiles for the same namespace, for example, the call will return the expected constant path for each of them without raising.
1418
+
1419
+ <a id="markdown-encodings" name="encodings"></a>
1420
+ ### Encodings
1421
+
1422
+ Zeitwerk supports projects whose files and file system are in UTF-8. The encoding of the file system can be checked this way:
1423
+
1424
+ ```
1425
+ % ruby -e "puts Encoding.find('filesystem')"
1426
+ UTF-8
1427
+ ```
1428
+
1429
+ 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.
567
1430
 
568
1431
  <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
569
1432
  ### Rules of thumb
@@ -574,21 +1437,12 @@ This only affects explicit namespaces, those idioms work well for any other ordi
574
1437
 
575
1438
  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.
576
1439
 
577
- 4. Projects that reopen a namespace defined by some dependency have to ensure said namespace is loaded before setup. That is, the project has to make sure it reopens, rather than define. This is often accomplished just loading the dependency.
1440
+ 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.
578
1441
 
579
1442
  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.
580
1443
 
581
1444
  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.
582
1445
 
583
- <a id="markdown-autoloading-explicit-namespaces-and-debuggers" name="autoloading-explicit-namespaces-and-debuggers"></a>
584
- ### Autoloading, explicit namespaces, and debuggers
585
-
586
- As of this writing, Zeitwerk is unable to autoload classes or modules that belong to [explicit namespaces](#explicit-namespaces) inside debugger sessions. You'll get a `NameError`.
587
-
588
- The root cause is that debuggers set trace points, and Zeitwerk does too to support explicit namespaces. A debugger session happens inside a trace point handler, and Ruby does not invoke other handlers from within a running handler. Therefore, the code that manages explicit namespaces in Zeitwerk does not get called by the interpreter. See [this issue](https://github.com/deivid-rodriguez/byebug/issues/564#issuecomment-499413606) for further details.
589
-
590
- As a workaround, you can eager load. Zeitwerk tries hard to succeed or fail consistently both autoloading and eager loading, so switching to eager loading should not introduce any interference in your debugging logic, generally speaking.
591
-
592
1446
  <a id="markdown-pronunciation" name="pronunciation"></a>
593
1447
  ## Pronunciation
594
1448
 
@@ -597,14 +1451,68 @@ As a workaround, you can eager load. Zeitwerk tries hard to succeed or fail cons
597
1451
  <a id="markdown-supported-ruby-versions" name="supported-ruby-versions"></a>
598
1452
  ## Supported Ruby versions
599
1453
 
600
- Zeitwerk works with MRI 2.4.4 and above.
1454
+ Starting with version 2.7, Zeitwerk requires Ruby 3.2 or newer.
1455
+
1456
+ Zeitwerk 2.7 requires TruffleRuby 24.1.2+ due to https://github.com/oracle/truffleruby/issues/3683.
1457
+ Alternatively, TruffleRuby users can use a `< 2.7` version constraint for the `zeitwerk` gem.
1458
+ As of this writing, [autoloading is not fully thread-safe yet on TruffleRuby](https://github.com/oracle/truffleruby/issues/2431).
1459
+ If your program is multi-threaded, you need to eager load before threads are created.
1460
+
1461
+ JRuby 9.3.0.0 is almost there. As of this writing, the test suite of Zeitwerk passes on JRuby except for three tests. (See https://github.com/jruby/jruby/issues/6781.)
1462
+
1463
+ <a id="markdown-testing" name="testing"></a>
1464
+ ## Testing
1465
+
1466
+ In order to run the test suite of Zeitwerk, `cd` into the project root and execute
1467
+
1468
+ ```
1469
+ bin/test
1470
+ ```
1471
+
1472
+ To run one particular suite, pass its file name as an argument:
1473
+
1474
+ ```
1475
+ bin/test test/lib/zeitwerk/test_eager_load.rb
1476
+ ```
1477
+
1478
+ That also accepts a line number:
1479
+
1480
+ ```
1481
+ bin/test test/lib/zeitwerk/test_eager_load.rb:52
1482
+ ```
1483
+
1484
+ Furthermore, the project has a development dependency on [`minitest-focus`](https://github.com/seattlerb/minitest-focus). To run an individual test mark it with `focus`:
1485
+
1486
+ ```ruby
1487
+ focus
1488
+ test 'capitalizes the first letter' do
1489
+ assert_equal 'User', camelize('user')
1490
+ end
1491
+ ```
1492
+
1493
+ and run `bin/test`.
601
1494
 
602
1495
  <a id="markdown-motivation" name="motivation"></a>
603
1496
  ## Motivation
604
1497
 
605
- 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. Zeitwerk provides a way to forget about `require` in your own code, just name things following conventions and done.
1498
+ <a id="markdown-kernelrequire-is-brittle" name="kernelrequire-is-brittle"></a>
1499
+ ### Kernel#require is brittle
606
1500
 
607
- On the other hand, autoloading in Rails is based on `const_missing`, which lacks fundamental information like the nesting and the resolution algorithm that was being used. Because of that, Rails autoloading is not able to match Ruby's semantics and that introduces a series of gotchas. The original goal of this project was to bring a better autoloading mechanism for Rails 6.
1501
+ 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.
1502
+
1503
+ 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.
1504
+
1505
+ 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.
1506
+
1507
+ <a id="markdown-rails-autoloading-was-brittle" name="rails-autoloading-was-brittle"></a>
1508
+ ### Rails autoloading was brittle
1509
+
1510
+ Autoloading in Rails was based on `const_missing` up to Rails 5. That callback lacks fundamental information like the nesting or the resolution algorithm being used. Because of that, Rails autoloading was not able to match Ruby's semantics, and that introduced a [series of issues](https://guides.rubyonrails.org/v5.2/autoloading_and_reloading_constants.html#common-gotchas). Zeitwerk is based on a different technique and fixed Rails autoloading starting with Rails 6.
1511
+
1512
+ <a id="markdown-awards" name="awards"></a>
1513
+ ## Awards
1514
+
1515
+ Zeitwerk has been awarded an "Outstanding Performance Award" Fukuoka Ruby Award 2022.
608
1516
 
609
1517
  <a id="markdown-thanks" name="thanks"></a>
610
1518
  ## Thanks
@@ -613,6 +1521,8 @@ I'd like to thank [@matthewd](https://github.com/matthewd) for the discussions w
613
1521
 
614
1522
  Also, would like to thank [@Shopify](https://github.com/Shopify), [@rafaelfranca](https://github.com/rafaelfranca), and [@dylanahsmith](https://github.com/dylanahsmith), for sharing [this PoC](https://github.com/Shopify/autoload_reloader). The technique Zeitwerk uses to support explicit namespaces was copied from that project.
615
1523
 
1524
+ Jean Boussier ([@casperisfine](https://github.com/casperisfine), [@byroot](https://github.com/byroot)) deserves special mention. Jean migrated autoloading in Shopify when Zeitwerk integration in Rails was yet unreleased. His work and positive attitude have been outstanding, and thanks to his feedback the interface and performance of Zeitwerk are way, way better. Kudos man ❤️.
1525
+
616
1526
  Finally, many thanks to [@schurig](https://github.com/schurig) for recording an [audio file](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3) with the pronunciation of "Zeitwerk" in perfect German. 💯
617
1527
 
618
1528
  <a id="markdown-license" name="license"></a>