zeitwerk 2.7.3 → 2.8.3

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: 1500c4f54c6ac7e64eef74c8702682764fa845533a5b16c67a48ee11781ef3e0
4
- data.tar.gz: f7201576b8b59ab3786cd4bc6fd58f3cd3afa3d8dcc1e86477121000f06ac50a
3
+ metadata.gz: '09d86092f7d624a602f7045e71ba3f835f76f1ad52da348b8e10994fbd3684b0'
4
+ data.tar.gz: 2a7dcbc6d655264553a0250161de1ffbb2e50da398acab939706ca849e43422c
5
5
  SHA512:
6
- metadata.gz: ab113d90c9a42ec5c75c6ebe68ab5a04395f1b33228de42de6952f2e673a329f30de85477977ec11d582df82f40c4dc5c08e8ba2305f46a6d07ac4e88c564887
7
- data.tar.gz: 73fb9dc78a9a7148119b306f93a513f841e4888d421fbf178963bbfa1368a8c7c66cd8661a28e8d95d14f51dab16fb4ff886f23183ec13a74847c45c1850f30d
6
+ metadata.gz: 38bc072945e9974b7029f87e73c71ea68c9be38c9b5d56a93a5e588e91adb22d037f7a83dc272d835d932463cb189385810311cfe8b8e284e301d1850f7507b7
7
+ data.tar.gz: 7e52df9e4c481e5a560cbf2a5ca5d0cf5ac3242a799bc29d52fa6420b3e65153afcc0ce96eb36bb215fb354defcdd71d8b0853c53586c8103d7930d08b1ddf7c
data/README.md CHANGED
@@ -19,6 +19,8 @@
19
19
  - [Nested root directories](#nested-root-directories)
20
20
  - [Implicit namespaces](#implicit-namespaces)
21
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)
22
24
  - [Collapsing directories](#collapsing-directories)
23
25
  - [Testing compliance](#testing-compliance)
24
26
  - [Usage](#usage)
@@ -58,6 +60,7 @@
58
60
  - [Reopening third-party namespaces](#reopening-third-party-namespaces)
59
61
  - [Introspection](#introspection)
60
62
  - [`Zeitwerk::Loader#dirs`](#zeitwerkloaderdirs)
63
+ - [Autoloaded Constants](#autoloaded-constants)
61
64
  - [`Zeitwerk::Loader#cpath_expected_at`](#zeitwerkloadercpath_expected_at)
62
65
  - [`Zeitwerk::Loader#all_expected_cpaths`](#zeitwerkloaderall_expected_cpaths)
63
66
  - [Encodings](#encodings)
@@ -97,7 +100,7 @@ Main interface for gems:
97
100
  ```ruby
98
101
  # lib/my_gem.rb (main file)
99
102
 
100
- require "zeitwerk"
103
+ require 'zeitwerk'
101
104
  loader = Zeitwerk::Loader.for_gem
102
105
  loader.setup # ready!
103
106
 
@@ -180,7 +183,7 @@ end
180
183
  The first example needs a custom [inflection](#inflection) rule:
181
184
 
182
185
  ```ruby
183
- loader.inflector.inflect("max_retries" => "MAX_RETRIES")
186
+ loader.inflector.inflect('max_retries' => 'MAX_RETRIES')
184
187
  ```
185
188
 
186
189
  Otherwise, Zeitwerk would expect the file to define `MaxRetries`.
@@ -201,7 +204,7 @@ For example, given
201
204
 
202
205
  ```ruby
203
206
  loader.push_dir("#{__dir__}/models")
204
- loader.push_dir("#{__dir__}/serializers"))
207
+ loader.push_dir("#{__dir__}/serializers")
205
208
  ```
206
209
 
207
210
  these are the expected classes and modules being defined by these files:
@@ -219,8 +222,8 @@ Although `Object` is the most common root namespace, you have the flexibility to
219
222
  For example, given:
220
223
 
221
224
  ```ruby
222
- require "active_job"
223
- require "active_job/queue_adapters"
225
+ require 'active_job'
226
+ require 'active_job/queue_adapters'
224
227
  loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters)
225
228
  ```
226
229
 
@@ -263,16 +266,23 @@ To trigger this behavior, the directory must contain non-ignored Ruby files with
263
266
  <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
264
267
  ### Explicit namespaces
265
268
 
266
- 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:
267
275
 
268
276
  ```
269
277
  app/models/hotel.rb -> Hotel
270
278
  app/models/hotel/pricing.rb -> Hotel::Pricing
271
279
  ```
272
280
 
273
- 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.
274
284
 
275
- 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:
276
286
 
277
287
  ```ruby
278
288
  class Hotel < ApplicationRecord
@@ -283,7 +293,48 @@ end
283
293
 
284
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.
285
295
 
286
- 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.
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`):
300
+
301
+ ```ruby
302
+ loader.nsfile = 'ns.rb' # must be set before setup
303
+ ```
304
+
305
+ you can alternatively define the explicit namespace inside its directory:
306
+
307
+ ```
308
+ my_component/ns.rb -> MyComponent
309
+ my_component/widget.rb -> MyComponent::Widget
310
+ ```
311
+
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`.
287
338
 
288
339
  <a id="markdown-collapsing-directories" name="collapsing-directories"></a>
289
340
  ### Collapsing directories
@@ -371,9 +422,9 @@ Conceptually, `for_gem` translates to:
371
422
  ```ruby
372
423
  # lib/my_gem.rb
373
424
 
374
- require "zeitwerk"
425
+ require 'zeitwerk'
375
426
  loader = Zeitwerk::Loader.new
376
- loader.tag = File.basename(__FILE__, ".rb")
427
+ loader.tag = File.basename(__FILE__, '.rb')
377
428
  loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
378
429
  loader.push_dir(File.dirname(__FILE__))
379
430
  ```
@@ -383,7 +434,7 @@ If the main module references project constants at the top-level, Zeitwerk has t
383
434
  ```ruby
384
435
  # lib/my_gem.rb (main file)
385
436
 
386
- require "zeitwerk"
437
+ require 'zeitwerk'
387
438
  loader = Zeitwerk::Loader.for_gem
388
439
  loader.setup
389
440
 
@@ -429,7 +480,7 @@ Let's suppose you are writing a gem to extend `Net::HTTP` with some niche featur
429
480
  The top-level file mentioned in the last point is optional. In particular, from
430
481
 
431
482
  ```ruby
432
- gem "net-http-niche_feature"
483
+ gem 'net-http-niche_feature'
433
484
  ```
434
485
 
435
486
  if the hyphenated file does not exist, Bundler notes the conventional hyphenated pattern and issues a `require` for `net/http/niche_feature`.
@@ -442,13 +493,13 @@ The structure of the gem would be like this:
442
493
  # lib/net-http-niche_feature.rb (optional)
443
494
 
444
495
  # For technical reasons, this cannot be require_relative.
445
- require "net/http/niche_feature"
496
+ require 'net/http/niche_feature'
446
497
 
447
498
 
448
499
  # lib/net/http/niche_feature.rb
449
500
 
450
- require "net/http"
451
- require "zeitwerk"
501
+ require 'net/http'
502
+ require 'zeitwerk'
452
503
 
453
504
  loader = Zeitwerk::Loader.for_gem_extension(Net::HTTP)
454
505
  loader.setup
@@ -463,7 +514,7 @@ end
463
514
  # lib/net/http/niche_feature/version.rb
464
515
 
465
516
  module Net::HTTP::NicheFeature
466
- VERSION = "1.0.0"
517
+ VERSION = '1.0.0'
467
518
  end
468
519
  ```
469
520
 
@@ -485,7 +536,7 @@ Let's revisit the example above:
485
536
  ```ruby
486
537
  # lib/my_gem.rb (main file)
487
538
 
488
- require "zeitwerk"
539
+ require 'zeitwerk'
489
540
  loader = Zeitwerk::Loader.for_gem
490
541
  loader.setup
491
542
 
@@ -494,7 +545,7 @@ module MyGem
494
545
  end
495
546
  ```
496
547
 
497
- That works, and there is no `require "my_gem/my_logger"`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
548
+ That works, and there is no `require 'my_gem/my_logger'`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
498
549
 
499
550
  If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
500
551
 
@@ -681,7 +732,7 @@ In order to reload safely, no other thread can be autoloading or reloading concu
681
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:
682
733
 
683
734
  ```ruby
684
- require "concurrent/atomic/read_write_lock"
735
+ require 'concurrent/atomic/read_write_lock'
685
736
 
686
737
  MyFramework::RELOAD_RW_LOCK = Concurrent::ReadWriteLock.new
687
738
  ```
@@ -726,22 +777,22 @@ The camelize logic can be overridden easily for individual basenames:
726
777
 
727
778
  ```ruby
728
779
  loader.inflector.inflect(
729
- "html_parser" => "HTMLParser",
730
- "mysql_adapter" => "MySQLAdapter"
780
+ 'html_parser' => 'HTMLParser',
781
+ 'mysql_adapter' => 'MySQLAdapter'
731
782
  )
732
783
  ```
733
784
 
734
785
  The `inflect` method can be invoked several times if you prefer this other style:
735
786
 
736
787
  ```ruby
737
- loader.inflector.inflect "html_parser" => "HTMLParser"
738
- loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
788
+ loader.inflector.inflect 'html_parser' => 'HTMLParser'
789
+ loader.inflector.inflect 'mysql_adapter' => 'MySQLAdapter'
739
790
  ```
740
791
 
741
792
  Overrides have to match exactly directory or file (without extension) _basenames_. For example, if you configure
742
793
 
743
794
  ```ruby
744
- loader.inflector.inflect("xml" => "XML")
795
+ loader.inflector.inflect('xml' => 'XML')
745
796
  ```
746
797
 
747
798
  then the following constants are expected:
@@ -756,8 +807,8 @@ As you see, any directory whose basename is exactly `xml`, and any file whose ba
756
807
 
757
808
  ```ruby
758
809
  loader.inflector.inflect(
759
- "xml" => "XML",
760
- "xml_parser" => "XMLParser"
810
+ 'xml' => 'XML',
811
+ 'xml_parser' => 'XMLParser'
761
812
  )
762
813
  ```
763
814
 
@@ -812,7 +863,7 @@ The inflectors that ship with Zeitwerk are deterministic and simple. But you can
812
863
  class MyInflector < Zeitwerk::Inflector
813
864
  def camelize(basename, abspath)
814
865
  if basename =~ /\Ahtml_(.*)/
815
- "HTML" + super($1, abspath)
866
+ 'HTML' + super($1, abspath)
816
867
  else
817
868
  super
818
869
  end
@@ -843,8 +894,8 @@ module MyGem
843
894
  end
844
895
 
845
896
  # lib/my_gem.rb
846
- require "zeitwerk"
847
- require_relative "my_gem/inflector"
897
+ require 'zeitwerk'
898
+ require_relative 'my_gem/inflector'
848
899
 
849
900
  loader = Zeitwerk::Loader.for_gem
850
901
  loader.inflector = MyGem::Inflector.new(__FILE__)
@@ -912,13 +963,13 @@ With `on_load`, it is easy to schedule code at boot time that initializes `endpo
912
963
 
913
964
  ```ruby
914
965
  # config/environments/development.rb
915
- loader.on_load("SomeApiClient") do |klass, _abspath|
916
- klass.endpoint = "https://api.dev"
966
+ loader.on_load('SomeApiClient') do |klass, _abspath|
967
+ klass.endpoint = 'https://api.dev'
917
968
  end
918
969
 
919
970
  # config/environments/production.rb
920
- loader.on_load("SomeApiClient") do |klass, _abspath|
921
- klass.endpoint = "https://api.prod"
971
+ loader.on_load('SomeApiClient') do |klass, _abspath|
972
+ klass.endpoint = 'https://api.prod'
922
973
  end
923
974
  ```
924
975
 
@@ -962,7 +1013,7 @@ When reloading is enabled, you may occasionally need to execute something before
962
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:
963
1014
 
964
1015
  ```ruby
965
- loader.on_unload("Country") do |klass, _abspath|
1016
+ loader.on_unload('Country') do |klass, _abspath|
966
1017
  klass.clear_cache
967
1018
  end
968
1019
  ```
@@ -1047,7 +1098,7 @@ Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
1047
1098
  By default, a random tag like the one above is assigned, but you can change it:
1048
1099
 
1049
1100
  ```
1050
- loader.tag = "grep_me"
1101
+ loader.tag = 'grep_me'
1051
1102
  ```
1052
1103
 
1053
1104
  The tag of a loader returned by `for_gem` is the basename of the root file without extension:
@@ -1103,7 +1154,7 @@ loader.setup
1103
1154
  Now, that file has to be loaded manually with `require` or `require_relative`:
1104
1155
 
1105
1156
  ```ruby
1106
- require_relative "my_gem/core_ext/kernel"
1157
+ require_relative 'my_gem/core_ext/kernel'
1107
1158
  ```
1108
1159
 
1109
1160
  and you can do that anytime, before configuring the loader, or after configuring the loader, does not matter.
@@ -1117,7 +1168,7 @@ Let's imagine your project talks to databases, supports several, and has adapter
1117
1168
 
1118
1169
  ```ruby
1119
1170
  # my_gem/db_adapters/postgresql.rb
1120
- require "pg"
1171
+ require 'pg'
1121
1172
  ```
1122
1173
 
1123
1174
  but you don't want your users to install them all, only the one they are going to use.
@@ -1155,7 +1206,7 @@ loader.setup
1155
1206
  In Ruby, if you have several files called `foo.rb` in different directories of `$LOAD_PATH` and execute
1156
1207
 
1157
1208
  ```ruby
1158
- require "foo"
1209
+ require 'foo'
1159
1210
  ```
1160
1211
 
1161
1212
  the first one found gets loaded, and the rest are ignored.
@@ -1224,10 +1275,10 @@ In order to do so, you need to make sure those modules are loaded before calling
1224
1275
 
1225
1276
  ```ruby
1226
1277
  # Ensure these namespaces are reopened, not defined.
1227
- require "active_job"
1228
- require "active_job/queue_adapters"
1278
+ require 'active_job'
1279
+ require 'active_job/queue_adapters'
1229
1280
 
1230
- require "zeitwerk"
1281
+ require 'zeitwerk'
1231
1282
  # By passing the flag, we acknowledge the extra directory lib/active_job
1232
1283
  # has to be managed by the loader and no warning has to be issued for it.
1233
1284
  loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
@@ -1246,23 +1297,35 @@ The method `Zeitwerk::Loader#dirs` returns an array with the absolute paths of t
1246
1297
 
1247
1298
  ```ruby
1248
1299
  loader = Zeitwerk::Loader.new
1249
- loader.push_dir(Pathname.new("/foo"))
1250
- loader.dirs # => ["/foo"]
1300
+ loader.push_dir(Pathname.new('/foo'))
1301
+ loader.dirs # => ['/foo']
1251
1302
  ```
1252
1303
 
1253
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:
1254
1305
 
1255
1306
  ```ruby
1256
1307
  loader = Zeitwerk::Loader.new
1257
- loader.push_dir(Pathname.new("/foo"))
1258
- loader.push_dir(Pathname.new("/bar"), namespace: Bar)
1259
- loader.dirs(namespaces: true) # => { "/foo" => Object, "/bar" => Bar }
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 }
1260
1311
  ```
1261
1312
 
1262
1313
  By default, ignored root directories are filtered out. If you want them included, please pass `ignored: true`.
1263
1314
 
1264
1315
  These collections are read-only. Please add to them with `Zeitwerk::Loader#push_dir`.
1265
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
1326
+ end
1327
+ ```
1328
+
1266
1329
  <a id="markdown-zeitwerkloadercpath_expected_at" name="zeitwerkloadercpath_expected_at"></a>
1267
1330
  #### `Zeitwerk::Loader#cpath_expected_at`
1268
1331
 
@@ -1271,18 +1334,18 @@ Given a path as a string or `Pathname` object, `Zeitwerk::Loader#cpath_expected_
1271
1334
  Some examples, assuming that `app/models` is a root directory:
1272
1335
 
1273
1336
  ```ruby
1274
- loader.cpath_expected_at("app/models") # => "Object"
1275
- loader.cpath_expected_at("app/models/user.rb") # => "User"
1276
- loader.cpath_expected_at("app/models/hotel") # => "Hotel"
1277
- loader.cpath_expected_at("app/models/hotel/billing.rb") # => "Hotel::Billing"
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'
1278
1341
  ```
1279
1342
 
1280
1343
  If `collapsed` is a collapsed directory:
1281
1344
 
1282
1345
  ```ruby
1283
- loader.cpath_expected_at("a/b/collapsed/c") # => "A::B::C"
1284
- loader.cpath_expected_at("a/b/collapsed") # => "A::B", edge case
1285
- loader.cpath_expected_at("a/b") # => "A::B"
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'
1286
1349
  ```
1287
1350
 
1288
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.
@@ -1290,16 +1353,18 @@ If the argument corresponds to an [ignored file or directory](#ignoring-parts-of
1290
1353
  `Zeitwerk::Error` is raised if the given path does not exist:
1291
1354
 
1292
1355
  ```ruby
1293
- loader.cpath_expected_at("non_existing_file.rb") # => Zeitwerk::Error
1356
+ loader.cpath_expected_at('non_existing_file.rb') # => Zeitwerk::Error
1294
1357
  ```
1295
1358
 
1296
1359
  `Zeitwerk::NameError` is raised if a constant path cannot be derived from it:
1297
1360
 
1298
1361
  ```ruby
1299
- loader.cpath_expected_at("8.rb") # => Zeitwerk::NameError
1362
+ loader.cpath_expected_at('8.rb') # => Zeitwerk::NameError
1300
1363
  ```
1301
1364
 
1302
- 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.
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.
1303
1368
 
1304
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.
1305
1370
 
@@ -1316,10 +1381,10 @@ For example, if `lib` is the root directory of a gem with the following contents
1316
1381
  lib/.DS_Store
1317
1382
  lib/my_gem.rb
1318
1383
  lib/my_gem/version.rb
1319
- lib/my_gem/ignored.rb
1320
1384
  lib/my_gem/drivers/unix.rb
1321
1385
  lib/my_gem/drivers/windows.rb
1322
1386
  lib/my_gem/collapsed/foo.rb
1387
+ lib/my_gem/ignored.rb
1323
1388
  lib/tasks/my_gem.rake
1324
1389
  ```
1325
1390
 
@@ -1327,27 +1392,29 @@ lib/tasks/my_gem.rake
1327
1392
 
1328
1393
  ```ruby
1329
1394
  {
1330
- "/.../lib" => "Object",
1331
- "/.../lib/my_gem.rb" => "MyGem",
1332
- "/.../lib/my_gem" => "MyGem",
1333
- "/.../lib/my_gem/version.rb" => "MyGem::VERSION",
1334
- "/.../lib/my_gem/drivers" => "MyGem::Drivers",
1335
- "/.../lib/my_gem/drivers/unix.rb" => "MyGem::Drivers::Unix",
1336
- "/.../lib/my_gem/drivers/windows.rb" => "MyGem::Drivers::Windows",
1337
- "/.../lib/my_gem/collapsed" => "MyGem"
1338
- "/.../lib/my_gem/collapsed/foo.rb" => "MyGem::Foo"
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'
1339
1404
  }
1340
1405
  ```
1341
1406
 
1342
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).
1343
1408
 
1344
- 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".
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".
1345
1410
 
1346
1411
  Directory paths do not have trailing slashes.
1347
1412
 
1348
1413
  The order of the hash entries is undefined.
1349
1414
 
1350
- 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.
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.
1351
1418
 
1352
1419
  <a id="markdown-encodings" name="encodings"></a>
1353
1420
  ### Encodings
@@ -1408,12 +1475,18 @@ To run one particular suite, pass its file name as an argument:
1408
1475
  bin/test test/lib/zeitwerk/test_eager_load.rb
1409
1476
  ```
1410
1477
 
1478
+ That also accepts a line number:
1479
+
1480
+ ```
1481
+ bin/test test/lib/zeitwerk/test_eager_load.rb:52
1482
+ ```
1483
+
1411
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`:
1412
1485
 
1413
1486
  ```ruby
1414
1487
  focus
1415
- test "capitalizes the first letter" do
1416
- assert_equal "User", camelize("user")
1488
+ test 'capitalizes the first letter' do
1489
+ assert_equal 'User', camelize('user')
1417
1490
  end
1418
1491
  ```
1419
1492
 
@@ -1427,7 +1500,7 @@ and run `bin/test`.
1427
1500
 
1428
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.
1429
1502
 
1430
- 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.
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.
1431
1504
 
1432
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.
1433
1506
 
@@ -22,7 +22,7 @@ module Kernel
22
22
  #: (String) -> bool
23
23
  def require(path)
24
24
  if loader = Zeitwerk::Registry.autoloads.registered?(path)
25
- if path.end_with?(".rb")
25
+ if path.end_with?('.rb')
26
26
  required = zeitwerk_original_require(path)
27
27
  loader.__on_file_autoloaded(path) if required
28
28
  required
@@ -17,7 +17,7 @@
17
17
  # For example, if we store values 0, 1, and 2 for the crefs that would
18
18
  # correspond to `M::X`, `M::Y`, and `N::Z`, the map will look like this:
19
19
  #
20
- # { M => { X: 0, :Y => 1 }, N => { Z: 2 } }
20
+ # { M => { X: 0, Y: 1 }, N => { Z: 2 } }
21
21
  #
22
22
  # This structure is internal, so only the needed interface is implemented.
23
23
  #
@@ -27,7 +27,7 @@
27
27
  # 1. We could also use a 1-level hash whose keys are constant paths. In the
28
28
  # example above it would be:
29
29
  #
30
- # { "M::X" => 0, "M::Y" => 1, "N::Z" => 2 }
30
+ # { 'M::X' => 0, 'M::Y' => 1, 'N::Z' => 2 }
31
31
  #
32
32
  # The gem used this approach for several years.
33
33
  #
@@ -44,7 +44,7 @@
44
44
  #
45
45
  # as hash code instead.
46
46
  #
47
- # Benchamrks
47
+ # Benchmarks
48
48
  # ----------
49
49
  #
50
50
  # Writing:
data/lib/zeitwerk/cref.rb CHANGED
@@ -11,7 +11,7 @@
11
11
  #
12
12
  # The constant may or may not exist in `mod`.
13
13
  class Zeitwerk::Cref
14
- require_relative "cref/map"
14
+ require_relative 'cref/map'
15
15
 
16
16
  include Zeitwerk::RealModName
17
17
 
@@ -66,4 +66,11 @@ class Zeitwerk::Cref
66
66
  def remove
67
67
  @mod.__send__(:remove_const, @cname)
68
68
  end
69
+
70
+ #: () -> String?
71
+ def location
72
+ if (location = @mod.const_source_location(@cname)) && !location.empty?
73
+ location.join(':')
74
+ end
75
+ end
69
76
  end
@@ -17,7 +17,18 @@ module Zeitwerk
17
17
  class SetupRequired < Error
18
18
  #: () -> void
19
19
  def initialize
20
- super("please, finish your configuration and call Zeitwerk::Loader#setup once all is ready")
20
+ super('please, finish your configuration and call Zeitwerk::Loader#setup once all is ready')
21
+ end
22
+ end
23
+
24
+ class ConflictingNamespaceDefinitionError < Error
25
+ #: (String, location: String?, conflicting_file: String) -> void
26
+ def initialize(cpath, location:, conflicting_file:)
27
+ if location
28
+ super("conflicting namespace definition for #{cpath}: #{conflicting_file} conflicts with #{location}")
29
+ else
30
+ super("conflicting namespace definition for #{cpath}: #{conflicting_file} conflicts with an already defined namespace")
31
+ end
21
32
  end
22
33
  end
23
34
  end
@@ -4,14 +4,14 @@ module Zeitwerk
4
4
  class GemInflector < Inflector
5
5
  #: (String) -> void
6
6
  def initialize(root_file)
7
- namespace = File.basename(root_file, ".rb")
7
+ namespace = File.basename(root_file, '.rb')
8
8
  root_dir = File.dirname(root_file)
9
- @version_file = File.join(root_dir, namespace, "version.rb")
9
+ @version_file = File.join(root_dir, namespace, 'version.rb')
10
10
  end
11
11
 
12
12
  #: (String, String) -> String
13
13
  def camelize(basename, abspath)
14
- abspath == @version_file ? "VERSION" : super
14
+ abspath == @version_file ? 'VERSION' : super
15
15
  end
16
16
  end
17
17
  end
@@ -19,8 +19,8 @@ module Zeitwerk
19
19
  def initialize(root_file, namespace:, warn_on_extra_files:)
20
20
  super()
21
21
 
22
- @tag = File.basename(root_file, ".rb")
23
- @tag = real_mod_name(namespace) + "-" + @tag unless namespace.equal?(Object)
22
+ @tag = File.basename(root_file, '.rb')
23
+ @tag = real_mod_name(namespace) + '-' + @tag unless namespace.equal?(Object)
24
24
 
25
25
  @inflector = GemInflector.new(root_file)
26
26
  @root_file = File.expand_path(root_file)
@@ -40,14 +40,14 @@ module Zeitwerk
40
40
 
41
41
  #: () -> void
42
42
  def warn_on_extra_files
43
- expected_namespace_dir = @root_file.delete_suffix(".rb")
43
+ expected_namespace_dir = @root_file.delete_suffix('.rb')
44
44
 
45
- ls(@root_dir) do |basename, abspath, ftype|
45
+ @fs.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
- basename_without_ext = basename.delete_suffix(".rb")
50
- cname = inflector.camelize(basename_without_ext, abspath).to_sym
49
+ basename_without_ext = basename.delete_suffix('.rb')
50
+ cname = cname_for(basename_without_ext, abspath)
51
51
 
52
52
  warn(<<~EOS)
53
53
  WARNING: Zeitwerk defines the constant #{cname} after the #{ftype}