zeitwerk 2.2.1 → 2.4.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b7d5a0f54405ad45dd6afc9bf54bde579f66a75fb142cdbbfb5476157dd75493
4
- data.tar.gz: b81311bb19c3b699a6720a3bb3d6df503b858a439c5f1f2605e029117de36bcb
3
+ metadata.gz: b0c408b8f6001e150b16b1e06b1b05d31bcbf4f0144535c995093c822065be3d
4
+ data.tar.gz: af26de0ecd68b8ebc1836ea431d59c6d7e10d79937c402e3529fc4275631c950
5
5
  SHA512:
6
- metadata.gz: 4f6fd6e8f7bd479ca6935d1f57d065151aff3be6977ad068f6b4ecdce200bbd131f4db4f2cc1bc2a719cb332b538cf24be55eb936a51572ac5c06676d21763f2
7
- data.tar.gz: d4266c65e380b356ff4df7394f2f1882f72ac32b5226dedd717f6b4064c8ac1b8fd3d70ec08b6f9838debfc3690d2f3eee2d6885e446f087a686a619c872c718
6
+ metadata.gz: 012c9a70cd31973a7251f46f62c102bf11155a6ea90dcdfa62bb2cd1859fca07cfed268dd130528fc55eab4ea0d440347e7ed0cb78f54dca861f96f56014541d
7
+ data.tar.gz: 7243c0f9b6c39dd389f0570fe03f11a8cadb01b74ae5d5efaa9b895ecf3b2717b5eb71e027c555f1cfeb95457dd5f5d8ace4516eb3a77500b05b1c8f973c1a94
data/README.md CHANGED
@@ -12,11 +12,15 @@
12
12
  - [File structure](#file-structure)
13
13
  - [Implicit namespaces](#implicit-namespaces)
14
14
  - [Explicit namespaces](#explicit-namespaces)
15
+ - [Collapsing directories](#collapsing-directories)
15
16
  - [Nested root directories](#nested-root-directories)
16
17
  - [Usage](#usage)
17
18
  - [Setup](#setup)
18
- - [Reloading](#reloading)
19
+ - [Generic](#generic)
20
+ - [for_gem](#for_gem)
21
+ - [Autoloading](#autoloading)
19
22
  - [Eager loading](#eager-loading)
23
+ - [Reloading](#reloading)
20
24
  - [Inflection](#inflection)
21
25
  - [Zeitwerk::Inflector](#zeitwerkinflector)
22
26
  - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
@@ -28,8 +32,11 @@
28
32
  - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
29
33
  - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
30
34
  - [Edge cases](#edge-cases)
35
+ - [Reopening third-party namespaces](#reopening-third-party-namespaces)
31
36
  - [Rules of thumb](#rules-of-thumb)
32
- - [Autoloading, explicit namespaces, and debuggers](#autoloading-explicit-namespaces-and-debuggers)
37
+ - [Debuggers](#debuggers)
38
+ - [Break](#break)
39
+ - [Byebug](#byebug)
33
40
  - [Pronunciation](#pronunciation)
34
41
  - [Supported Ruby versions](#supported-ruby-versions)
35
42
  - [Testing](#testing)
@@ -50,7 +57,9 @@ Zeitwerk is also able to reload code, which may be handy while developing web ap
50
57
 
51
58
  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.
52
59
 
53
- 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.
60
+ 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`.
61
+
62
+ Furthermore, Zeitwerk does at most one single scan of the project tree, and it descends into subdirectories lazily, only if their namespaces are used.
54
63
 
55
64
  <a id="markdown-synopsis" name="synopsis"></a>
56
65
  ## Synopsis
@@ -130,6 +139,22 @@ app/models/user.rb -> User
130
139
  app/controllers/admin/users_controller.rb -> Admin::UsersController
131
140
  ```
132
141
 
142
+ Alternatively, you can associate a custom namespace to a root directory by passing a class or module object in the optional `namespace` keyword argument.
143
+
144
+ For example, Active Job queue adapters have to define a constant after their name in `ActiveJob::QueueAdapters`.
145
+
146
+ So, if you declare
147
+
148
+ ```ruby
149
+ require "active_job"
150
+ require "active_job/queue_adapters"
151
+ loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters)
152
+ ```
153
+
154
+ your adapter can be stored directly in that directory instead of the canonical `#{__dir__}/active_job/queue_adapters`.
155
+
156
+ Please, note that the given 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::V2::Deliveries`, that one can be reloaded.
157
+
133
158
  <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
134
159
  ### Implicit namespaces
135
160
 
@@ -164,6 +189,32 @@ end
164
189
 
165
190
  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.
166
191
 
192
+ <a id="markdown-collapsing-directories" name="collapsing-directories"></a>
193
+ ### Collapsing directories
194
+
195
+ 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:
196
+
197
+ ```
198
+ booking.rb -> Booking
199
+ booking/actions/create.rb -> Booking::Create
200
+ ```
201
+
202
+ To make it work that way, configure Zeitwerk to collapse said directory:
203
+
204
+ ```ruby
205
+ loader.collapse("#{__dir__}/booking/actions")
206
+ ```
207
+
208
+ This method accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
209
+
210
+ You can pass directories and glob patterns. Glob patterns are expanded when they are added, and again on each reload.
211
+
212
+ To illustrate usage of glob patterns, if `actions` in the example above is part of a standardized structure, you could use a wildcard:
213
+
214
+ ```ruby
215
+ loader.collapse("#{__dir__}/*/actions")
216
+ ```
217
+
167
218
  <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
168
219
  ### Nested root directories
169
220
 
@@ -183,6 +234,9 @@ should define `Geolocatable`, not `Concerns::Geolocatable`.
183
234
  <a id="markdown-setup" name="setup"></a>
184
235
  ### Setup
185
236
 
237
+ <a id="markdown-generic" name="generic"></a>
238
+ #### Generic
239
+
186
240
  Loaders are ready to load code right after calling `setup` on them:
187
241
 
188
242
  ```ruby
@@ -199,9 +253,36 @@ loader.push_dir(...)
199
253
  loader.setup
200
254
  ```
201
255
 
202
- 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.
256
+ <a id="markdown-for_gem" name="for_gem"></a>
257
+ #### for_gem
203
258
 
204
- 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:
259
+ `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:
260
+
261
+ ```
262
+ lib/my_gem.rb # MyGem
263
+ lib/my_gem/version.rb # MyGem::VERSION
264
+ lib/my_gem/foo.rb # MyGem::Foo
265
+ ```
266
+
267
+ Neither a gemspec nor a version file are technically required, this helper works as long as the code is organized using that standard structure.
268
+
269
+ 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_](https://github.com/fxn/zeitwerk#reopening-third-party-namespaces) down below.
270
+
271
+ Conceptually, `for_gem` translates to:
272
+
273
+ ```ruby
274
+ # lib/my_gem.rb
275
+
276
+ require "zeitwerk"
277
+ loader = Zeitwerk::Loader.new
278
+ loader.tag = File.basename(__FILE__, ".rb")
279
+ loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
280
+ loader.push_dir(__dir__)
281
+ ```
282
+
283
+ except that this method returns the same object in subsequent calls from the same file, in the unlikely case the gem wants to be able to reload.
284
+
285
+ 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:
205
286
 
206
287
  ```ruby
207
288
  # lib/my_gem.rb (main file)
@@ -217,35 +298,28 @@ module MyGem
217
298
  end
218
299
  ```
219
300
 
220
- 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.
301
+ <a id="markdown-autoloading" name="autoloading"></a>
302
+ ### Autoloading
221
303
 
222
- <a id="markdown-reloading" name="reloading"></a>
223
- ### Reloading
304
+ 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.
224
305
 
225
- Zeitwerk is able to reload code, but you need to enable this feature:
306
+ Let's revisit the example above:
226
307
 
227
308
  ```ruby
228
- loader = Zeitwerk::Loader.new
229
- loader.push_dir(...)
230
- loader.enable_reloading # you need to opt-in before setup
231
- loader.setup
232
- ...
233
- loader.reload
234
- ```
235
-
236
- There is no way to undo this, either you want to reload or you don't.
237
-
238
- Enabling reloading after setup raises `Zeitwerk::Error`. Similarly, calling `reload` without having enabled reloading also raises `Zeitwerk::Error`.
239
-
240
- 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.
309
+ # lib/my_gem.rb (main file)
241
310
 
242
- Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
311
+ require "zeitwerk"
312
+ loader = Zeitwerk::Loader.for_gem
313
+ loader.setup
243
314
 
244
- It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
315
+ module MyGem
316
+ include MyLogger # (*)
317
+ end
318
+ ```
245
319
 
246
- 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.
320
+ That works, and there is no `require "my_gem/my_logger"`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
247
321
 
248
- 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.
322
+ If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
249
323
 
250
324
  <a id="markdown-eager-loading" name="eager-loading"></a>
251
325
  ### Eager loading
@@ -269,6 +343,8 @@ In gems, the method needs to be invoked after the main namespace has been define
269
343
 
270
344
  Eager loading is synchronized and idempotent.
271
345
 
346
+ If eager loading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
347
+
272
348
  If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
273
349
 
274
350
  ```ruby
@@ -279,6 +355,34 @@ This may be handy in top-level services, like web applications.
279
355
 
280
356
  Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
281
357
 
358
+ <a id="markdown-reloading" name="reloading"></a>
359
+ ### Reloading
360
+
361
+ Zeitwerk is able to reload code, but you need to enable this feature:
362
+
363
+ ```ruby
364
+ loader = Zeitwerk::Loader.new
365
+ loader.push_dir(...)
366
+ loader.enable_reloading # you need to opt-in before setup
367
+ loader.setup
368
+ ...
369
+ loader.reload
370
+ ```
371
+
372
+ There is no way to undo this, either you want to reload or you don't.
373
+
374
+ Enabling reloading after setup raises `Zeitwerk::Error`. Attempting to reload without having it enabled raises `Zeitwerk::ReloadingDisabledError`.
375
+
376
+ 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.
377
+
378
+ Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
379
+
380
+ It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
381
+
382
+ 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.
383
+
384
+ 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.
385
+
282
386
  <a id="markdown-inflection" name="inflection"></a>
283
387
  ### Inflection
284
388
 
@@ -566,6 +670,42 @@ Trip = Struct.new { ... } # NOT SUPPORTED
566
670
 
567
671
  This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
568
672
 
673
+ <a id="markdown-reopening-third-party-namespaces" name="reopening-third-party-namespaces"></a>
674
+ ### Reopening third-party namespaces
675
+
676
+ Projects managed by Zeitwerk can work with namespaces defined by third-party libraries. However, they have to be loaded in memory before calling `setup`.
677
+
678
+ 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:
679
+
680
+ ```ruby
681
+ # lib/active_job/queue_adapters/awesome_queue.rb
682
+ module ActiveJob
683
+ module QueueAdapters
684
+ class AwesomeQueue
685
+ # ...
686
+ end
687
+ end
688
+ end
689
+ ```
690
+
691
+ 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.
692
+
693
+ Bottom line, Zeitwerk should not be managing those namespaces. Active Job owns them and defines them. Your gem needs to _reopen_ them.
694
+
695
+ 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:
696
+
697
+ ```ruby
698
+ # Ensure these namespaces are reopened, not defined.
699
+ require "active_job"
700
+ require "active_job/queue_adapters"
701
+
702
+ require "zeitwerk"
703
+ loader = Zeitwerk::Loader.for_gem
704
+ loader.setup
705
+ ```
706
+
707
+ 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.
708
+
569
709
  <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
570
710
  ### Rules of thumb
571
711
 
@@ -581,14 +721,18 @@ This only affects explicit namespaces, those idioms work well for any other ordi
581
721
 
582
722
  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.
583
723
 
584
- <a id="markdown-autoloading-explicit-namespaces-and-debuggers" name="autoloading-explicit-namespaces-and-debuggers"></a>
585
- ### Autoloading, explicit namespaces, and debuggers
724
+ <a id="markdown-debuggers" name="debuggers"></a>
725
+ ### Debuggers
726
+
727
+ <a id="markdown-break" name="break"></a>
728
+ #### Break
586
729
 
587
- 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`.
730
+ Zeitwerk works fine with [@gsamokovarov](https://github.com/gsamokovarov)'s [Break](https://github.com/gsamokovarov/break) debugger.
588
731
 
589
- 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.
732
+ <a id="markdown-byebug" name="byebug"></a>
733
+ #### Byebug
590
734
 
591
- 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.
735
+ Zeitwerk and [Byebug](https://github.com/deivid-rodriguez/byebug) are incompatible, classes or modules that belong to [explicit namespaces](#explicit-namespaces) are not autoloaded inside a Byebug session. See [this issue](https://github.com/deivid-rodriguez/byebug/issues/564#issuecomment-499413606) for further details.
592
736
 
593
737
  <a id="markdown-pronunciation" name="pronunciation"></a>
594
738
  ## Pronunciation
@@ -14,24 +14,22 @@ module Zeitwerk
14
14
  # the file system, to the loader responsible for them.
15
15
  #
16
16
  # @private
17
- # @return [{String => Zeitwerk::Loader}]
17
+ # @sig Hash[String, Zeitwerk::Loader]
18
18
  attr_reader :cpaths
19
19
 
20
20
  # @private
21
- # @return [Mutex]
21
+ # @sig Mutex
22
22
  attr_reader :mutex
23
23
 
24
24
  # @private
25
- # @return [TracePoint]
25
+ # @sig TracePoint
26
26
  attr_reader :tracer
27
27
 
28
28
  # Asserts `cpath` corresponds to an explicit namespace for which `loader`
29
29
  # is responsible.
30
30
  #
31
31
  # @private
32
- # @param cpath [String]
33
- # @param loader [Zeitwerk::Loader]
34
- # @return [void]
32
+ # @sig (String, Zeitwerk::Loader) -> void
35
33
  def register(cpath, loader)
36
34
  mutex.synchronize do
37
35
  cpaths[cpath] = loader
@@ -42,19 +40,22 @@ module Zeitwerk
42
40
  end
43
41
 
44
42
  # @private
45
- # @param loader [Zeitwerk::Loader]
46
- # @return [void]
43
+ # @sig (Zeitwerk::Loader) -> void
47
44
  def unregister(loader)
48
45
  cpaths.delete_if { |_cpath, l| l == loader }
49
46
  disable_tracer_if_unneeded
50
47
  end
51
48
 
49
+ private
50
+
51
+ # @sig () -> void
52
52
  def disable_tracer_if_unneeded
53
53
  mutex.synchronize do
54
54
  tracer.disable if cpaths.empty?
55
55
  end
56
56
  end
57
57
 
58
+ # @sig (TracePoint) -> void
58
59
  def tracepoint_class_callback(event)
59
60
  # If the class is a singleton class, we won't do anything with it so we
60
61
  # can bail out immediately. This is several orders of magnitude faster
@@ -2,16 +2,14 @@
2
2
 
3
3
  module Zeitwerk
4
4
  class GemInflector < Inflector
5
- # @param root_file [String]
5
+ # @sig (String) -> void
6
6
  def initialize(root_file)
7
7
  namespace = File.basename(root_file, ".rb")
8
8
  lib_dir = File.dirname(root_file)
9
9
  @version_file = File.join(lib_dir, namespace, "version.rb")
10
10
  end
11
11
 
12
- # @param basename [String]
13
- # @param abspath [String]
14
- # @return [String]
12
+ # @sig (String, String) -> String
15
13
  def camelize(basename, abspath)
16
14
  abspath == @version_file ? "VERSION" : super
17
15
  end
@@ -11,11 +11,9 @@ module Zeitwerk
11
11
  #
12
12
  # Takes into account hard-coded mappings configured with `inflect`.
13
13
  #
14
- # @param basename [String]
15
- # @param _abspath [String]
16
- # @return [String]
14
+ # @sig (String, String) -> String
17
15
  def camelize(basename, _abspath)
18
- overrides[basename] || basename.split('_').map!(&:capitalize).join
16
+ overrides[basename] || basename.split('_').each(&:capitalize!).join
19
17
  end
20
18
 
21
19
  # Configures hard-coded inflections:
@@ -30,8 +28,7 @@ module Zeitwerk
30
28
  # inflector.camelize("mysql_adapter", abspath) # => "MySQLAdapter"
31
29
  # inflector.camelize("users_controller", abspath) # => "UsersController"
32
30
  #
33
- # @param inflections [{String => String}]
34
- # @return [void]
31
+ # @sig (Hash[String, String]) -> void
35
32
  def inflect(inflections)
36
33
  overrides.merge!(inflections)
37
34
  end
@@ -41,7 +38,7 @@ module Zeitwerk
41
38
  # Hard-coded basename to constant name user maps that override the default
42
39
  # inflection logic.
43
40
  #
44
- # @return [{String => String}]
41
+ # @sig () -> Hash[String, String]
45
42
  def overrides
46
43
  @overrides ||= {}
47
44
  end
@@ -3,13 +3,23 @@
3
3
  module Kernel
4
4
  module_function
5
5
 
6
+ # We are going to decorate Kerner#require with two goals.
7
+ #
8
+ # First, by intercepting Kernel#require calls, we are able to autovivify
9
+ # modules on required directories, and also do internal housekeeping when
10
+ # managed files are loaded.
11
+ #
12
+ # On the other hand, if you publish a new version of a gem that is now managed
13
+ # by Zeitwerk, client code can reference directly your classes and modules and
14
+ # should not require anything. But if someone has legacy require calls around,
15
+ # they will work as expected, and in a compatible way.
16
+ #
6
17
  # We cannot decorate with prepend + super because Kernel has already been
7
18
  # included in Object, and changes in ancestors don't get propagated into
8
19
  # already existing ancestor chains.
9
20
  alias_method :zeitwerk_original_require, :require
10
21
 
11
- # @param path [String]
12
- # @return [Boolean]
22
+ # @sig (String) -> true | false
13
23
  def require(path)
14
24
  if loader = Zeitwerk::Registry.loader_for(path)
15
25
  if path.end_with?(".rb")
@@ -30,4 +40,24 @@ module Kernel
30
40
  end
31
41
  end
32
42
  end
43
+
44
+ # By now, I have seen no way so far to decorate require_relative.
45
+ #
46
+ # For starters, at least in CRuby, require_relative does not delegate to
47
+ # require. Both require and require_relative delegate the bulk of their work
48
+ # to an internal C function called rb_require_safe. So, our require wrapper is
49
+ # not executed.
50
+ #
51
+ # On the other hand, we cannot use the aliasing technique above because
52
+ # require_relative receives a path relative to the directory of the file in
53
+ # which the call is performed. If a wrapper here invoked the original method,
54
+ # Ruby would resolve the relative path taking lib/zeitwerk as base directory.
55
+ #
56
+ # A workaround could be to extract the base directory from caller_locations,
57
+ # but what if someone else decorated require_relative before us? You can't
58
+ # really know with certainty where's the original call site in the stack.
59
+ #
60
+ # However, the main use case for require_relative is to load files from your
61
+ # own project. Projects managed by Zeitwerk don't do this for files managed by
62
+ # Zeitwerk, precisely.
33
63
  end