zeitwerk 2.6.8 → 2.6.18

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 418f16f6224359c716a990f72ae916c980a3f388b09ab018c0972b8558530620
4
- data.tar.gz: '04847c6c8f8f894fe3c2b3c39d175b5854b583d3a02ef5cca27a53cb1b8dafd4'
3
+ metadata.gz: a1fa60f08c282d8471eaf321deba97207ce56d2cba32619cff78f09e65f2f258
4
+ data.tar.gz: 1c803846848fc8830913acfd8fbf04bfa59f26c3c8806d4fa5bed9c751f48c5a
5
5
  SHA512:
6
- metadata.gz: f86272e84721cf9b8b1e07182b1b60cfe732ef2c266dbe076225d32af52fc9a30c278a14651ddbb3d435636646dd23c948d3fe0f00ed9b8393abdeb34dd40028
7
- data.tar.gz: 562738b53779310e899c2065c7046844d27daabb5f354972e4c9b65bec3e5c0cdade92d19ed815fe7b0dc01538603daa3e4dd2f0049fe9a7a2e74313c0f040f6
6
+ metadata.gz: abb7134976f1ae00cafd77dcaa39fe2239632639c136d866ac75e55c8ec15f1c157ff0e434969dade286ee36e6422856799acd3e86dcd61e4ef39d1fd23909a4
7
+ data.tar.gz: 42e2309bd69f0bba3bfc74acecf2fcf3b3206a6cd26583afdc1012d34a063431bc03ec4ec42e1cf452f41bfa0de43a4d171cb2e99c7ca3e64b61412fbef83819
data/README.md CHANGED
@@ -3,7 +3,8 @@
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/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%3main)
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
 
@@ -39,6 +40,7 @@
39
40
  - [Inflection](#inflection)
40
41
  - [Zeitwerk::Inflector](#zeitwerkinflector)
41
42
  - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
43
+ - [Zeitwerk::NullInflector](#zeitwerknullinflector)
42
44
  - [Custom inflector](#custom-inflector)
43
45
  - [Callbacks](#callbacks)
44
46
  - [The on_setup callback](#the-on_setup-callback)
@@ -56,6 +58,9 @@
56
58
  - [Beware of circular dependencies](#beware-of-circular-dependencies)
57
59
  - [Reopening third-party namespaces](#reopening-third-party-namespaces)
58
60
  - [Introspection](#introspection)
61
+ - [`Zeitwerk::Loader#dirs`](#zeitwerkloaderdirs)
62
+ - [`Zeitwerk::Loader#cpath_expected_at`](#zeitwerkloadercpath_expected_at)
63
+ - [`Zeitwerk::Loader#all_expected_cpaths`](#zeitwerkloaderall_expected_cpaths)
59
64
  - [Encodings](#encodings)
60
65
  - [Rules of thumb](#rules-of-thumb)
61
66
  - [Debuggers](#debuggers)
@@ -76,15 +81,15 @@
76
81
 
77
82
  Zeitwerk is an efficient and thread-safe code loader for Ruby.
78
83
 
79
- 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.
84
+ 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.
80
85
 
81
- 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.
86
+ 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.
82
87
 
83
- 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.
88
+ 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.
84
89
 
85
- 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`.
90
+ 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`.
86
91
 
87
- Furthermore, Zeitwerk does at most one single scan of the project tree, and it descends into subdirectories lazily, only if their namespaces are used.
92
+ Furthermore, Zeitwerk performs a single scan of the project tree at most, lazily descending into subdirectories only when their namespaces are used.
88
93
 
89
94
  <a id="markdown-synopsis" name="synopsis"></a>
90
95
  ## Synopsis
@@ -144,7 +149,7 @@ Zeitwerk::Loader.eager_load_all
144
149
  <a id="markdown-the-idea-file-paths-match-constant-paths" name="the-idea-file-paths-match-constant-paths"></a>
145
150
  ### The idea: File paths match constant paths
146
151
 
147
- To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
152
+ For Zeitwerk to work with your file structure, simply name files and directories after the classes and modules they define:
148
153
 
149
154
  ```
150
155
  lib/my_gem.rb -> MyGem
@@ -153,7 +158,7 @@ lib/my_gem/bar_baz.rb -> MyGem::BarBaz
153
158
  lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
154
159
  ```
155
160
 
156
- You can tune that a bit by [collapsing directories](#collapsing-directories), or by [ignoring parts of the project](#ignoring-parts-of-the-project), but that is the main idea.
161
+ 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.
157
162
 
158
163
  <a id="markdown-inner-simple-constants" name="inner-simple-constants"></a>
159
164
  ### Inner simple constants
@@ -211,7 +216,7 @@ serializers/user_serializer.rb -> UserSerializer
211
216
  <a id="markdown-custom-root-namespaces" name="custom-root-namespaces"></a>
212
217
  #### Custom root namespaces
213
218
 
214
- While `Object` is by far the most common root namespace, you can associate a different one to a particular root directory. The method `push_dir` accepts a non-anonymous class or module object in the optional `namespace` keyword argument.
219
+ 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.
215
220
 
216
221
  For example, given:
217
222
 
@@ -227,14 +232,14 @@ a file defining `ActiveJob::QueueAdapters::MyQueueAdapter` does not need the con
227
232
  adapters/my_queue_adapter.rb -> ActiveJob::QueueAdapters::MyQueueAdapter
228
233
  ```
229
234
 
230
- Please, note that the given root namespace must be non-reloadable, though autoloaded constants in that namespace can be. That is, if you associate `app/api` with an existing `Api` module, that module should not be reloadable. However, if the project defines and autoloads the class `Api::Deliveries`, that one can be reloaded.
235
+ 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.
231
236
 
232
237
  <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
233
238
  #### Nested root directories
234
239
 
235
- 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.
240
+ 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.
236
241
 
237
- 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:
242
+ 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:
238
243
 
239
244
  ```
240
245
  app/models/concerns/geolocatable.rb
@@ -245,9 +250,9 @@ should define `Geolocatable`, not `Concerns::Geolocatable`.
245
250
  <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
246
251
  ### Implicit namespaces
247
252
 
248
- If a namespace is just a simple module with no code, you do not need to define it in a file: Directories without a matching Ruby file get modules created automatically on your behalf.
253
+ 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.
249
254
 
250
- For example, if a project has an `admin` directory:
255
+ For instance, suppose a project includes an `admin` directory:
251
256
 
252
257
  ```
253
258
  app/controllers/admin/users_controller.rb -> Admin::UsersController
@@ -255,7 +260,7 @@ app/controllers/admin/users_controller.rb -> Admin::UsersController
255
260
 
256
261
  and does not have a file called `admin.rb`, Zeitwerk automatically creates an `Admin` module on your behalf the first time `Admin` is used.
257
262
 
258
- For this to happen, the directory has to contain non-ignored Ruby files with extension `.rb`, directly or recursively, otherwise it is ignored. This condition is evaluated again on reloads.
263
+ 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.
259
264
 
260
265
  <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
261
266
  ### Explicit namespaces
@@ -370,7 +375,7 @@ require "zeitwerk"
370
375
  loader = Zeitwerk::Loader.new
371
376
  loader.tag = File.basename(__FILE__, ".rb")
372
377
  loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
373
- loader.push_dir(__dir__)
378
+ loader.push_dir(File.dirname(__FILE__))
374
379
  ```
375
380
 
376
381
  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:
@@ -576,7 +581,7 @@ root_dir2/my_app/routes
576
581
  root_dir3/my_app/routes
577
582
  ```
578
583
 
579
- where `root_directory{1,2,3}` are root directories, eager loading `MyApp::Routes` will eager load the contents of the three corresponding directories.
584
+ where `root_dir{1,2,3}` are root directories, eager loading `MyApp::Routes` will eager load the contents of the three corresponding directories.
580
585
 
581
586
  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.
582
587
 
@@ -733,9 +738,34 @@ loader.inflector.inflect "html_parser" => "HTMLParser"
733
738
  loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
734
739
  ```
735
740
 
741
+ Overrides have to match exactly directory or file (without extension) _basenames_. For example, if you configure
742
+
743
+ ```ruby
744
+ loader.inflector.inflect("xml" => "XML")
745
+ ```
746
+
747
+ then the following constants are expected:
748
+
749
+ ```
750
+ xml.rb -> XML
751
+ foo/xml -> Foo::XML
752
+ foo/bar/xml.rb -> Foo::Bar::XML
753
+ ```
754
+
755
+ 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:
756
+
757
+ ```ruby
758
+ loader.inflector.inflect(
759
+ "xml" => "XML",
760
+ "xml_parser" => "XMLParser"
761
+ )
762
+ ```
763
+
764
+ If you need more flexibility, you can define a custom inflector, as explained down below.
765
+
736
766
  Overrides need to be configured before calling `setup`.
737
767
 
738
- 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.
768
+ 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.
739
769
 
740
770
  <a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
741
771
  #### Zeitwerk::GemInflector
@@ -746,6 +776,31 @@ This inflector is like the basic one, except it expects `lib/my_gem/version.rb`
746
776
 
747
777
  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.
748
778
 
779
+ <a id="markdown-zeitwerknullinflector" name="zeitwerknullinflector"></a>
780
+ #### Zeitwerk::NullInflector
781
+
782
+ This is an experimental inflector that simply returns its input unchanged.
783
+
784
+ ```ruby
785
+ loader.inflector = Zeitwerk::NullInflector.new
786
+ ```
787
+
788
+ In a project using this inflector, the names of files and directories are equal to the constants they define:
789
+
790
+ ```
791
+ User.rb -> User
792
+ HTMLParser.rb -> HTMLParser
793
+ Admin/Role.rb -> Admin::Role
794
+ ```
795
+
796
+ 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.
797
+
798
+ 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!
799
+
800
+ 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.
801
+
802
+ 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`.
803
+
749
804
  <a id="markdown-custom-inflector" name="custom-inflector"></a>
750
805
  #### Custom inflector
751
806
 
@@ -978,7 +1033,7 @@ Zeitwerk::Loader.default_logger = method(:puts)
978
1033
 
979
1034
  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.
980
1035
 
981
- 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.
1036
+ 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.
982
1037
 
983
1038
  <a id="markdown-loader-tag" name="loader-tag"></a>
984
1039
  #### Loader tag
@@ -1004,13 +1059,13 @@ Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
1004
1059
  <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
1005
1060
  ### Ignoring parts of the project
1006
1061
 
1007
- Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
1062
+ Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have the extension ".rb".
1008
1063
 
1009
1064
  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.
1010
1065
 
1011
1066
  You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
1012
1067
 
1013
- There is an edge case related to nested root directories. Conceptually, root directories are independent source trees. If you ignore a parent of a nested root directory, the nested root directory is not affected. You need to ignore it explictly if you want it ignored too.
1068
+ 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.
1014
1069
 
1015
1070
  Let's see some use cases.
1016
1071
 
@@ -1214,6 +1269,9 @@ With that, when Zeitwerk scans the file system and reaches the gem directories `
1214
1269
  <a id="markdown-introspection" name="introspection"></a>
1215
1270
  ### Introspection
1216
1271
 
1272
+ <a id="markdown-zeitwerkloaderdirs" name="zeitwerkloaderdirs"></a>
1273
+ #### `Zeitwerk::Loader#dirs`
1274
+
1217
1275
  The method `Zeitwerk::Loader#dirs` returns an array with the absolute paths of the root directories as strings:
1218
1276
 
1219
1277
  ```ruby
@@ -1235,6 +1293,92 @@ By default, ignored root directories are filtered out. If you want them included
1235
1293
 
1236
1294
  These collections are read-only. Please add to them with `Zeitwerk::Loader#push_dir`.
1237
1295
 
1296
+ <a id="markdown-zeitwerkloadercpath_expected_at" name="zeitwerkloadercpath_expected_at"></a>
1297
+ #### `Zeitwerk::Loader#cpath_expected_at`
1298
+
1299
+ Given a path as a string or `Pathname` object, `Zeitwerk::Loader#cpath_expected_at` returns a string with the corresponding expected constant path.
1300
+
1301
+ Some examples, assuming that `app/models` is a root directory:
1302
+
1303
+ ```ruby
1304
+ loader.cpath_expected_at("app/models") # => "Object"
1305
+ loader.cpath_expected_at("app/models/user.rb") # => "User"
1306
+ loader.cpath_expected_at("app/models/hotel") # => "Hotel"
1307
+ loader.cpath_expected_at("app/models/hotel/billing.rb") # => "Hotel::Billing"
1308
+ ```
1309
+
1310
+ If `collapsed` is a collapsed directory:
1311
+
1312
+ ```ruby
1313
+ loader.cpath_expected_at("a/b/collapsed/c") # => "A::B::C"
1314
+ loader.cpath_expected_at("a/b/collapsed") # => "A::B", edge case
1315
+ loader.cpath_expected_at("a/b") # => "A::B"
1316
+ ```
1317
+
1318
+ 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.
1319
+
1320
+ `Zeitwerk::Error` is raised if the given path does not exist:
1321
+
1322
+ ```ruby
1323
+ loader.cpath_expected_at("non_existing_file.rb") # => Zeitwerk::Error
1324
+ ```
1325
+
1326
+ `Zeitwerk::NameError` is raised if a constant path cannot be derived from it:
1327
+
1328
+ ```ruby
1329
+ loader.cpath_expected_at("8.rb") # => Zeitwerk::NameError
1330
+ ```
1331
+
1332
+ 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.
1333
+
1334
+ `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.
1335
+
1336
+ <a id="markdown-zeitwerkloaderall_expected_cpaths" name="zeitwerkloaderall_expected_cpaths"></a>
1337
+ #### `Zeitwerk::Loader#all_expected_cpaths`
1338
+
1339
+ 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.
1340
+
1341
+ 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.
1342
+
1343
+ For example, if `lib` is the root directory of a gem with the following contents:
1344
+
1345
+ ```
1346
+ lib/.DS_Store
1347
+ lib/my_gem.rb
1348
+ lib/my_gem/version.rb
1349
+ lib/my_gem/ignored.rb
1350
+ lib/my_gem/drivers/unix.rb
1351
+ lib/my_gem/drivers/windows.rb
1352
+ lib/my_gem/collapsed/foo.rb
1353
+ lib/tasks/my_gem.rake
1354
+ ```
1355
+
1356
+ `Zeitwerk::Loader#all_expected_cpaths` would return (maybe in a different order):
1357
+
1358
+ ```ruby
1359
+ {
1360
+ "/.../lib" => "Object",
1361
+ "/.../lib/my_gem.rb" => "MyGem",
1362
+ "/.../lib/my_gem" => "MyGem",
1363
+ "/.../lib/my_gem/version.rb" => "MyGem::VERSION",
1364
+ "/.../lib/my_gem/drivers" => "MyGem::Drivers",
1365
+ "/.../lib/my_gem/drivers/unix.rb" => "MyGem::Drivers::Unix",
1366
+ "/.../lib/my_gem/drivers/windows.rb" => "MyGem::Drivers::Windows",
1367
+ "/.../lib/my_gem/collapsed" => "MyGem"
1368
+ "/.../lib/my_gem/collapsed/foo.rb" => "MyGem::Foo"
1369
+ }
1370
+ ```
1371
+
1372
+ 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).
1373
+
1374
+ 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".
1375
+
1376
+ Directory paths do not have trailing slashes.
1377
+
1378
+ The order of the hash entries is undefined.
1379
+
1380
+ 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.
1381
+
1238
1382
  <a id="markdown-encodings" name="encodings"></a>
1239
1383
  ### Encodings
1240
1384
 
@@ -1256,7 +1400,7 @@ The test suite passes on Windows with codepage `Windows-1252` if all the involve
1256
1400
 
1257
1401
  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.
1258
1402
 
1259
- 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.
1403
+ 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.
1260
1404
 
1261
1405
  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.
1262
1406
 
@@ -1265,9 +1409,11 @@ The test suite passes on Windows with codepage `Windows-1252` if all the involve
1265
1409
  <a id="markdown-debuggers" name="debuggers"></a>
1266
1410
  ### Debuggers
1267
1411
 
1268
- Zeitwerk works fine with [debug.rb](https://github.com/ruby/debug) and [Break](https://github.com/gsamokovarov/break).
1412
+ Zeitwerk and [debug.rb](https://github.com/ruby/debug) are fully compatible if CRuby is ≥ 3.1 (see [ruby/debug#558](https://github.com/ruby/debug/pull/558)).
1413
+
1414
+ [Byebug](https://github.com/deivid-rodriguez/byebug) is compatible except for an edge case explained in [deivid-rodriguez/byebug#564](https://github.com/deivid-rodriguez/byebug/issues/564). Prior to CRuby 3.1, `debug.rb` has a similar edge incompatibility.
1269
1415
 
1270
- [Byebug](https://github.com/deivid-rodriguez/byebug) is compatible except for an edge case explained in [deivid-rodriguez/byebug#564](https://github.com/deivid-rodriguez/byebug/issues/564).
1416
+ [Break](https://github.com/gsamokovarov/break) is fully compatible.
1271
1417
 
1272
1418
  <a id="markdown-pronunciation" name="pronunciation"></a>
1273
1419
  ## Pronunciation
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This private class encapsulates pairs (mod, cname).
4
+ #
5
+ # Objects represent the constant cname in the class or module object mod, and
6
+ # have API to manage them that encapsulates the constants API. Examples:
7
+ #
8
+ # cref.path
9
+ # cref.set(value)
10
+ # cref.get
11
+ #
12
+ # The constant may or may not exist in mod.
13
+ class Zeitwerk::Cref
14
+ include Zeitwerk::RealModName
15
+
16
+ # @sig Symbol
17
+ attr_reader :cname
18
+
19
+ # The type of the first argument is Module because Class < Module, class
20
+ # objects are also valid.
21
+ #
22
+ # @sig (Module, Symbol) -> void
23
+ def initialize(mod, cname)
24
+ @mod = mod
25
+ @cname = cname
26
+ @path = nil
27
+ end
28
+
29
+ if Symbol.method_defined?(:name)
30
+ # Symbol#name was introduced in Ruby 3.0. It returns always the same
31
+ # frozen object, so we may save a few string allocations.
32
+ #
33
+ # @sig () -> String
34
+ def path
35
+ @path ||= Object.equal?(@mod) ? @cname.name : "#{real_mod_name(@mod)}::#{@cname.name}"
36
+ end
37
+ else
38
+ # @sig () -> String
39
+ def path
40
+ @path ||= Object.equal?(@mod) ? @cname.to_s : "#{real_mod_name(@mod)}::#{@cname}"
41
+ end
42
+ end
43
+
44
+ # The autoload? predicate takes into account the ancestor chain of the
45
+ # receiver, like const_defined? and other methods in the constants API do.
46
+ #
47
+ # For example, given
48
+ #
49
+ # class A
50
+ # autoload :X, "x.rb"
51
+ # end
52
+ #
53
+ # class B < A
54
+ # end
55
+ #
56
+ # B.autoload?(:X) returns "x.rb".
57
+ #
58
+ # We need a way to retrieve it ignoring ancestors.
59
+ #
60
+ # @sig () -> String?
61
+ if method(:autoload?).arity == 1
62
+ # @sig () -> String?
63
+ def autoload?
64
+ @mod.autoload?(@cname) if self.defined?
65
+ end
66
+ else
67
+ # @sig () -> String?
68
+ def autoload?
69
+ @mod.autoload?(@cname, false)
70
+ end
71
+ end
72
+
73
+ # @sig (String) -> bool
74
+ def autoload(abspath)
75
+ @mod.autoload(@cname, abspath)
76
+ end
77
+
78
+ # @sig () -> bool
79
+ def defined?
80
+ @mod.const_defined?(@cname, false)
81
+ end
82
+
83
+ # @sig (Object) -> Object
84
+ def set(value)
85
+ @mod.const_set(@cname, value)
86
+ end
87
+
88
+ # @raise [NameError]
89
+ # @sig () -> Object
90
+ def get
91
+ @mod.const_get(@cname, false)
92
+ end
93
+
94
+ # @raise [NameError]
95
+ # @sig () -> void
96
+ def remove
97
+ @mod.__send__(:remove_const, @cname)
98
+ end
99
+ end
@@ -42,13 +42,12 @@ module Zeitwerk
42
42
  def warn_on_extra_files
43
43
  expected_namespace_dir = @root_file.delete_suffix(".rb")
44
44
 
45
- ls(@root_dir) do |basename, abspath|
45
+ ls(@root_dir) do |basename, abspath, ftype|
46
46
  next if abspath == @root_file
47
47
  next if abspath == expected_namespace_dir
48
48
 
49
49
  basename_without_ext = basename.delete_suffix(".rb")
50
50
  cname = inflector.camelize(basename_without_ext, abspath).to_sym
51
- ftype = dir?(abspath) ? "directory" : "file"
52
51
 
53
52
  warn(<<~EOS)
54
53
  WARNING: Zeitwerk defines the constant #{cname} after the #{ftype}
@@ -14,10 +14,6 @@ module Kernel
14
14
  # should not require anything. But if someone has legacy require calls around,
15
15
  # they will work as expected, and in a compatible way. This feature is by now
16
16
  # EXPERIMENTAL and UNDOCUMENTED.
17
- #
18
- # We cannot decorate with prepend + super because Kernel has already been
19
- # included in Object, and changes in ancestors don't get propagated into
20
- # already existing ancestor chains on Ruby < 3.0.
21
17
  alias_method :zeitwerk_original_require, :require
22
18
  class << self
23
19
  alias_method :zeitwerk_original_require, :require
@@ -28,10 +24,10 @@ module Kernel
28
24
  if loader = Zeitwerk::Registry.loader_for(path)
29
25
  if path.end_with?(".rb")
30
26
  required = zeitwerk_original_require(path)
31
- loader.on_file_autoloaded(path) if required
27
+ loader.__on_file_autoloaded(path) if required
32
28
  required
33
29
  else
34
- loader.on_dir_autoloaded(path)
30
+ loader.__on_dir_autoloaded(path)
35
31
  true
36
32
  end
37
33
  else
@@ -39,7 +35,7 @@ module Kernel
39
35
  if required
40
36
  abspath = $LOADED_FEATURES.last
41
37
  if loader = Zeitwerk::Registry.loader_for(abspath)
42
- loader.on_file_autoloaded(abspath)
38
+ loader.__on_file_autoloaded(abspath)
43
39
  end
44
40
  end
45
41
  required
@@ -2,38 +2,45 @@
2
2
 
3
3
  module Zeitwerk::Loader::Callbacks
4
4
  include Zeitwerk::RealModName
5
+ extend Zeitwerk::Internal
5
6
 
6
7
  # Invoked from our decorated Kernel#require when a managed file is autoloaded.
7
8
  #
8
- # @private
9
9
  # @sig (String) -> void
10
- def on_file_autoloaded(file)
11
- cref = autoloads.delete(file)
12
- cpath = cpath(*cref)
10
+ internal def on_file_autoloaded(file)
11
+ cref = autoloads.delete(file)
13
12
 
14
13
  Zeitwerk::Registry.unregister_autoload(file)
15
14
 
16
- if cdef?(*cref)
17
- log("constant #{cpath} loaded from file #{file}") if logger
18
- to_unload[cpath] = [file, cref] if reloading_enabled?
19
- run_on_load_callbacks(cpath, cget(*cref), file) unless on_load_callbacks.empty?
15
+ if cref.defined?
16
+ log("constant #{cref.path} loaded from file #{file}") if logger
17
+ to_unload[cref.path] = [file, cref] if reloading_enabled?
18
+ run_on_load_callbacks(cref.path, cref.get, file) unless on_load_callbacks.empty?
20
19
  else
21
- msg = "expected file #{file} to define constant #{cpath}, but didn't"
20
+ msg = "expected file #{file} to define constant #{cref.path}, but didn't"
22
21
  log(msg) if logger
23
- crem(*cref)
24
- to_unload[cpath] = [file, cref] if reloading_enabled?
25
- raise Zeitwerk::NameError.new(msg, cref.last)
22
+
23
+ # Ruby still keeps the autoload defined, but we remove it because the
24
+ # contract in Zeitwerk is more strict.
25
+ cref.remove
26
+
27
+ # Since the expected constant was not defined, there is nothing to unload.
28
+ # However, if the exception is rescued and reloading is enabled, we still
29
+ # need to deleted the file from $LOADED_FEATURES.
30
+ to_unload[cref.path] = [file, cref] if reloading_enabled?
31
+
32
+ raise Zeitwerk::NameError.new(msg, cref.cname)
26
33
  end
27
34
  end
28
35
 
29
36
  # Invoked from our decorated Kernel#require when a managed directory is
30
37
  # autoloaded.
31
38
  #
32
- # @private
33
39
  # @sig (String) -> void
34
- def on_dir_autoloaded(dir)
35
- # Module#autoload does not serialize concurrent requires, and we handle
36
- # directories ourselves, so the callback needs to account for concurrency.
40
+ internal def on_dir_autoloaded(dir)
41
+ # Module#autoload does not serialize concurrent requires in CRuby < 3.2, and
42
+ # we handle directories ourselves without going through Kernel#require, so
43
+ # the callback needs to account for concurrency.
37
44
  #
38
45
  # Multi-threading would introduce a race condition here in which thread t1
39
46
  # autovivifies the module, and while autoloads for its children are being
@@ -43,10 +50,10 @@ module Zeitwerk::Loader::Callbacks
43
50
  # That not only would reassign the constant (undesirable per se) but, worse,
44
51
  # the module object created by t2 wouldn't have any of the autoloads for its
45
52
  # children, since t1 would have correctly deleted its namespace_dirs entry.
46
- mutex2.synchronize do
53
+ dirs_autoload_monitor.synchronize do
47
54
  if cref = autoloads.delete(dir)
48
- autovivified_module = cref[0].const_set(cref[1], Module.new)
49
- cpath = autovivified_module.name
55
+ implicit_namespace = cref.set(Module.new)
56
+ cpath = implicit_namespace.name
50
57
  log("module #{cpath} autovivified from directory #{dir}") if logger
51
58
 
52
59
  to_unload[cpath] = [dir, cref] if reloading_enabled?
@@ -57,9 +64,9 @@ module Zeitwerk::Loader::Callbacks
57
64
  # these to be able to unregister later if eager loading.
58
65
  autoloaded_dirs << dir
59
66
 
60
- on_namespace_loaded(autovivified_module)
67
+ on_namespace_loaded(implicit_namespace)
61
68
 
62
- run_on_load_callbacks(cpath, autovivified_module, dir) unless on_load_callbacks.empty?
69
+ run_on_load_callbacks(cpath, implicit_namespace, dir) unless on_load_callbacks.empty?
63
70
  end
64
71
  end
65
72
  end
@@ -73,7 +80,7 @@ module Zeitwerk::Loader::Callbacks
73
80
  def on_namespace_loaded(namespace)
74
81
  if dirs = namespace_dirs.delete(real_mod_name(namespace))
75
82
  dirs.each do |dir|
76
- set_autoloads_in_dir(dir, namespace)
83
+ define_autoloads_for_dir(dir, namespace)
77
84
  end
78
85
  end
79
86
  end