zeitwerk 2.3.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b8fd1828e8e92937af8b1e46033442f517c65c07a443a9a265b67c03f22b8b86
4
+ data.tar.gz: 4e04076d6ac82d1bff9bf3db8604ca7e826afad753fb1268116cd115f15d301b
5
+ SHA512:
6
+ metadata.gz: cacd0d2c43a566a5e3be7dfb98585e9598a9fda8e930bb0f97a96180db332d6303fb1cfbf850f85dd822071968fc624262b94c27db85ad3e1236f1e243df64c2
7
+ data.tar.gz: 0f9c90d543eae10edade4777f63c02a0f5ef30ecfdfe752fc9f11e5f6e3c835d2b893b0e8074e4cd068859e41dcf6e5374527c73499876deab3a9974cd0d2bf4
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2019–ω Xavier Noria
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,703 @@
1
+ # Zeitwerk
2
+
3
+
4
+
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)
7
+
8
+ <!-- TOC -->
9
+
10
+ - [Introduction](#introduction)
11
+ - [Synopsis](#synopsis)
12
+ - [File structure](#file-structure)
13
+ - [Implicit namespaces](#implicit-namespaces)
14
+ - [Explicit namespaces](#explicit-namespaces)
15
+ - [Collapsing directories](#collapsing-directories)
16
+ - [Nested root directories](#nested-root-directories)
17
+ - [Usage](#usage)
18
+ - [Setup](#setup)
19
+ - [Autoloading](#autoloading)
20
+ - [Eager loading](#eager-loading)
21
+ - [Reloading](#reloading)
22
+ - [Inflection](#inflection)
23
+ - [Zeitwerk::Inflector](#zeitwerkinflector)
24
+ - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
25
+ - [Custom inflector](#custom-inflector)
26
+ - [Logging](#logging)
27
+ - [Loader tag](#loader-tag)
28
+ - [Ignoring parts of the project](#ignoring-parts-of-the-project)
29
+ - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
30
+ - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
31
+ - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
32
+ - [Edge cases](#edge-cases)
33
+ - [Rules of thumb](#rules-of-thumb)
34
+ - [Autoloading, explicit namespaces, and debuggers](#autoloading-explicit-namespaces-and-debuggers)
35
+ - [Pronunciation](#pronunciation)
36
+ - [Supported Ruby versions](#supported-ruby-versions)
37
+ - [Testing](#testing)
38
+ - [Motivation](#motivation)
39
+ - [Thanks](#thanks)
40
+ - [License](#license)
41
+
42
+ <!-- /TOC -->
43
+
44
+ <a id="markdown-introduction" name="introduction"></a>
45
+ ## Introduction
46
+
47
+ Zeitwerk is an efficient and thread-safe code loader for Ruby.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+ 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.
56
+
57
+ <a id="markdown-synopsis" name="synopsis"></a>
58
+ ## Synopsis
59
+
60
+ Main interface for gems:
61
+
62
+ ```ruby
63
+ # lib/my_gem.rb (main file)
64
+
65
+ require "zeitwerk"
66
+ loader = Zeitwerk::Loader.for_gem
67
+ loader.setup # ready!
68
+
69
+ module MyGem
70
+ # ...
71
+ end
72
+
73
+ loader.eager_load # optionally
74
+ ```
75
+
76
+ Main generic interface:
77
+
78
+ ```ruby
79
+ loader = Zeitwerk::Loader.new
80
+ loader.push_dir(...)
81
+ loader.setup # ready!
82
+ ```
83
+
84
+ The `loader` variable can go out of scope. Zeitwerk keeps a registry with all of them, and so the object won't be garbage collected.
85
+
86
+ You can reload if you want to:
87
+
88
+ ```ruby
89
+ loader = Zeitwerk::Loader.new
90
+ loader.push_dir(...)
91
+ loader.enable_reloading # you need to opt-in before setup
92
+ loader.setup
93
+ ...
94
+ loader.reload
95
+ ```
96
+
97
+ and you can eager load all the code:
98
+
99
+ ```ruby
100
+ loader.eager_load
101
+ ```
102
+
103
+ It is also possible to broadcast `eager_load` to all instances:
104
+
105
+ ```ruby
106
+ Zeitwerk::Loader.eager_load_all
107
+ ```
108
+
109
+ <a id="markdown-file-structure" name="file-structure"></a>
110
+ ## File structure
111
+
112
+ To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
113
+
114
+ ```
115
+ lib/my_gem.rb -> MyGem
116
+ lib/my_gem/foo.rb -> MyGem::Foo
117
+ lib/my_gem/bar_baz.rb -> MyGem::BarBaz
118
+ lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
119
+ ```
120
+
121
+ Every directory configured with `push_dir` acts as root namespace. There can be several of them. For example, given
122
+
123
+ ```ruby
124
+ loader.push_dir(Rails.root.join("app/models"))
125
+ loader.push_dir(Rails.root.join("app/controllers"))
126
+ ```
127
+
128
+ Zeitwerk understands that their respective files and subdirectories belong to the root namespace:
129
+
130
+ ```
131
+ app/models/user.rb -> User
132
+ app/controllers/admin/users_controller.rb -> Admin::UsersController
133
+ ```
134
+
135
+ <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
136
+ ### Implicit namespaces
137
+
138
+ Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
139
+
140
+ ```
141
+ app/controllers/admin/users_controller.rb -> Admin::UsersController
142
+ ```
143
+
144
+ `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.
145
+
146
+ <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
147
+ ### Explicit namespaces
148
+
149
+ Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
150
+
151
+ ```
152
+ app/models/hotel.rb -> Hotel
153
+ app/models/hotel/pricing.rb -> Hotel::Pricing
154
+ ```
155
+
156
+ There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
157
+
158
+ The classes and modules from the namespace are already available in the body of the class or module defining it:
159
+
160
+ ```ruby
161
+ class Hotel < ApplicationRecord
162
+ include Pricing # works
163
+ ...
164
+ end
165
+ ```
166
+
167
+ 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.
168
+
169
+ <a id="markdown-collapsing-directories" name="collapsing-directories"></a>
170
+ ### Collapsing directories
171
+
172
+ 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:
173
+
174
+ ```
175
+ booking.rb -> Booking
176
+ booking/actions/create.rb -> Booking::Create
177
+ ```
178
+
179
+ To make it work that way, configure Zeitwerk to collapse said directory:
180
+
181
+ ```ruby
182
+ loader.collapse("booking/actions")
183
+ ```
184
+
185
+ This method accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
186
+
187
+ You can pass directories and glob patterns. Glob patterns are expanded when they are added, and again on each reload.
188
+
189
+ To illustrate usage of glob patterns, if `actions` in the example above is part of a standardized structure, you could use a wildcard:
190
+
191
+ ```ruby
192
+ loader.collapse("*/actions")
193
+ ```
194
+
195
+ <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
196
+ ### Nested root directories
197
+
198
+ 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.
199
+
200
+ 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:
201
+
202
+ ```
203
+ app/models/concerns/geolocatable.rb
204
+ ```
205
+
206
+ should define `Geolocatable`, not `Concerns::Geolocatable`.
207
+
208
+ <a id="markdown-usage" name="usage"></a>
209
+ ## Usage
210
+
211
+ <a id="markdown-setup" name="setup"></a>
212
+ ### Setup
213
+
214
+ Loaders are ready to load code right after calling `setup` on them:
215
+
216
+ ```ruby
217
+ loader.setup
218
+ ```
219
+
220
+ This method is synchronized and idempotent.
221
+
222
+ Customization should generally be done before that call. In particular, in the generic interface you may set the root directories from which you want to load files:
223
+
224
+ ```ruby
225
+ loader.push_dir(...)
226
+ loader.push_dir(...)
227
+ loader.setup
228
+ ```
229
+
230
+ 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.
231
+
232
+ 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:
233
+
234
+ ```ruby
235
+ # lib/my_gem.rb (main file)
236
+
237
+ require "zeitwerk"
238
+ loader = Zeitwerk::Loader.for_gem
239
+ loader.setup
240
+
241
+ module MyGem
242
+ # Since the setup has been performed, at this point we are already able
243
+ # to reference project constants, in this case MyGem::MyLogger.
244
+ include MyLogger
245
+ end
246
+ ```
247
+
248
+ 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.
249
+
250
+ <a id="markdown-autoloading" name="autoloading"></a>
251
+ ### Autoloading
252
+
253
+ 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.
254
+
255
+ Let's revisit the example above:
256
+
257
+ ```ruby
258
+ # lib/my_gem.rb (main file)
259
+
260
+ require "zeitwerk"
261
+ loader = Zeitwerk::Loader.for_gem
262
+ loader.setup
263
+
264
+ module MyGem
265
+ include MyLogger # (*)
266
+ end
267
+ ```
268
+
269
+ That works, and there is no `require "my_gem/my_logger"`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
270
+
271
+ If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
272
+
273
+ <a id="markdown-eager-loading" name="eager-loading"></a>
274
+ ### Eager loading
275
+
276
+ Zeitwerk instances are able to eager load their managed files:
277
+
278
+ ```ruby
279
+ loader.eager_load
280
+ ```
281
+
282
+ 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:
283
+
284
+ ```ruby
285
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
286
+ loader.do_not_eager_load(db_adapters)
287
+ loader.setup
288
+ loader.eager_load # won't eager load the database adapters
289
+ ```
290
+
291
+ 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).
292
+
293
+ Eager loading is synchronized and idempotent.
294
+
295
+ If eager loading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
296
+
297
+ If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
298
+
299
+ ```ruby
300
+ Zeitwerk::Loader.eager_load_all
301
+ ```
302
+
303
+ This may be handy in top-level services, like web applications.
304
+
305
+ Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
306
+
307
+ <a id="markdown-reloading" name="reloading"></a>
308
+ ### Reloading
309
+
310
+ Zeitwerk is able to reload code, but you need to enable this feature:
311
+
312
+ ```ruby
313
+ loader = Zeitwerk::Loader.new
314
+ loader.push_dir(...)
315
+ loader.enable_reloading # you need to opt-in before setup
316
+ loader.setup
317
+ ...
318
+ loader.reload
319
+ ```
320
+
321
+ There is no way to undo this, either you want to reload or you don't.
322
+
323
+ Enabling reloading after setup raises `Zeitwerk::Error`. Attempting to reload without having it enabled raises `Zeitwerk::ReloadingDisabledError`.
324
+
325
+ 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.
326
+
327
+ Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
328
+
329
+ It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
330
+
331
+ 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.
332
+
333
+ 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.
334
+
335
+ <a id="markdown-inflection" name="inflection"></a>
336
+ ### Inflection
337
+
338
+ 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.
339
+
340
+ <a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
341
+ #### Zeitwerk::Inflector
342
+
343
+ This is a very basic inflector that converts snake case to camel case:
344
+
345
+ ```
346
+ user -> User
347
+ users_controller -> UsersController
348
+ html_parser -> HtmlParser
349
+ ```
350
+
351
+ The camelize logic can be overridden easily for individual basenames:
352
+
353
+ ```ruby
354
+ loader.inflector.inflect(
355
+ "html_parser" => "HTMLParser",
356
+ "mysql_adapter" => "MySQLAdapter"
357
+ )
358
+ ```
359
+
360
+ The `inflect` method can be invoked several times if you prefer this other style:
361
+
362
+ ```ruby
363
+ loader.inflector.inflect "html_parser" => "HTMLParser"
364
+ loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
365
+ ```
366
+
367
+ Overrides need to be configured before calling `setup`.
368
+
369
+ There are no inflection rules or global configuration that can affect this inflector. It is deterministic.
370
+
371
+ Loaders instantiated with `Zeitwerk::Loader.new` have an inflector of this type, independent of each other.
372
+
373
+ <a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
374
+ #### Zeitwerk::GemInflector
375
+
376
+ This inflector is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
377
+
378
+ Loaders instantiated with `Zeitwerk::Loader.for_gem` have an inflector of this type, independent of each other.
379
+
380
+ <a id="markdown-custom-inflector" name="custom-inflector"></a>
381
+ #### Custom inflector
382
+
383
+ The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
384
+
385
+ ```ruby
386
+ # frozen_string_literal: true
387
+
388
+ class MyInflector < Zeitwerk::Inflector
389
+ def camelize(basename, abspath)
390
+ if basename =~ /\Ahtml_(.*)/
391
+ "HTML" + super($1, abspath)
392
+ else
393
+ super
394
+ end
395
+ end
396
+ end
397
+ ```
398
+
399
+ The first argument, `basename`, is a string with the basename of the file or directory to be inflected. In the case of a file, without extension. In the case of a directory, without trailing slash. The inflector needs to return this basename inflected. Therefore, a simple constant name without colons.
400
+
401
+ The second argument, `abspath`, is a string with the absolute path to the file or directory in case you need it to decide how to inflect the basename. Paths to directories don't have trailing slashes.
402
+
403
+ Then, assign the inflector:
404
+
405
+ ```ruby
406
+ loader.inflector = MyInflector.new
407
+ ```
408
+
409
+ This needs to be done before calling `setup`.
410
+
411
+ If a custom inflector definition in a gem takes too much space in the main file, you can extract it. For example, this is a simple pattern:
412
+
413
+ ```ruby
414
+ # lib/my_gem/inflector.rb
415
+ module MyGem
416
+ class Inflector < Zeitwerk::GemInflector
417
+ ...
418
+ end
419
+ end
420
+
421
+ # lib/my_gem.rb
422
+ require "zeitwerk"
423
+ require_relative "my_gem/inflector"
424
+
425
+ loader = Zeitwerk::Loader.for_gem
426
+ loader.inflector = MyGem::Inflector.new(__FILE__)
427
+ loader.setup
428
+
429
+ module MyGem
430
+ # ...
431
+ end
432
+ ```
433
+
434
+ Since `MyGem` is referenced before the namespace is defined in the main file, it is important to use this style:
435
+
436
+ ```ruby
437
+ # Correct, effectively defines MyGem.
438
+ module MyGem
439
+ class Inflector < Zeitwerk::GemInflector
440
+ # ...
441
+ end
442
+ end
443
+ ```
444
+
445
+ instead of:
446
+
447
+ ```ruby
448
+ # Raises uninitialized constant MyGem (NameError).
449
+ class MyGem::Inflector < Zeitwerk::GemInflector
450
+ # ...
451
+ end
452
+ ```
453
+
454
+ <a id="markdown-logging" name="logging"></a>
455
+ ### Logging
456
+
457
+ Zeitwerk is silent by default, but you can ask loaders to trace their activity. Logging is meant just for troubleshooting, shouldn't normally be enabled.
458
+
459
+ The `log!` method is a quick shortcut to let the loader log to `$stdout`:
460
+
461
+ ```
462
+ loader.log!
463
+ ```
464
+
465
+ If you want more control, a logger can be configured as a callable
466
+
467
+ ```ruby
468
+ loader.logger = method(:puts)
469
+ loader.logger = ->(msg) { ... }
470
+ ```
471
+
472
+ as well as anything that responds to `debug`:
473
+
474
+ ```ruby
475
+ loader.logger = Logger.new($stderr)
476
+ loader.logger = Rails.logger
477
+ ```
478
+
479
+ In both cases, the corresponding methods are going to be passed exactly one argument with the message to be logged.
480
+
481
+ It is also possible to set a global default this way:
482
+
483
+ ```ruby
484
+ Zeitwerk::Loader.default_logger = method(:puts)
485
+ ```
486
+
487
+ 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.
488
+
489
+ 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.
490
+
491
+ <a id="markdown-loader-tag" name="loader-tag"></a>
492
+ #### Loader tag
493
+
494
+ Loaders have a tag that is printed in traces in order to be able to distinguish them in globally logged activity:
495
+
496
+ ```
497
+ Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
498
+ ```
499
+
500
+ By default, a random tag like the one above is assigned, but you can change it:
501
+
502
+ ```
503
+ loader.tag = "grep_me"
504
+ ```
505
+
506
+ The tag of a loader returned by `for_gem` is the basename of the root file without extension:
507
+
508
+ ```
509
+ Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
510
+ ```
511
+
512
+ <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
513
+ ### Ignoring parts of the project
514
+
515
+ Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
516
+
517
+ 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.
518
+
519
+ You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
520
+
521
+ Let's see some use cases.
522
+
523
+ <a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
524
+ #### Use case: Files that do not follow the conventions
525
+
526
+ Let's suppose that your gem decorates something in `Kernel`:
527
+
528
+ ```ruby
529
+ # lib/my_gem/core_ext/kernel.rb
530
+
531
+ Kernel.module_eval do
532
+ # ...
533
+ end
534
+ ```
535
+
536
+ That file does not define a constant path after the path name and you need to tell Zeitwerk:
537
+
538
+ ```ruby
539
+ kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
540
+ loader.ignore(kernel_ext)
541
+ loader.setup
542
+ ```
543
+
544
+ You can also ignore the whole directory:
545
+
546
+ ```ruby
547
+ core_ext = "#{__dir__}/my_gem/core_ext"
548
+ loader.ignore(core_ext)
549
+ loader.setup
550
+ ```
551
+
552
+ <a id="markdown-use-case-the-adapter-pattern" name="use-case-the-adapter-pattern"></a>
553
+ #### Use case: The adapter pattern
554
+
555
+ Another use case for ignoring files is the adapter pattern.
556
+
557
+ Let's imagine your project talks to databases, supports several, and has adapters for each one of them. Those adapters may have top-level `require` calls that load their respective drivers:
558
+
559
+ ```ruby
560
+ # my_gem/db_adapters/postgresql.rb
561
+ require "pg"
562
+ ```
563
+
564
+ but you don't want your users to install them all, only the one they are going to use.
565
+
566
+ On the other hand, if your code is eager loaded by you or a parent project (with `Zeitwerk::Loader.eager_load_all`), those `require` calls are going to be executed. Ignoring the adapters prevents that:
567
+
568
+ ```ruby
569
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
570
+ loader.ignore(db_adapters)
571
+ loader.setup
572
+ ```
573
+
574
+ The chosen adapter, then, has to be loaded by hand somehow:
575
+
576
+ ```ruby
577
+ require "my_gem/db_adapters/#{config[:db_adapter]}"
578
+ ```
579
+
580
+ Note that since the directory is ignored, the required adapter can instantiate another loader to manage its subtree, if desired. Such loader would coexist with the main one just fine.
581
+
582
+ <a id="markdown-use-case-test-files-mixed-with-implementation-files" name="use-case-test-files-mixed-with-implementation-files"></a>
583
+ #### Use case: Test files mixed with implementation files
584
+
585
+ There are project layouts that put implementation files and test files together. To ignore the test files, you can use a glob pattern like this:
586
+
587
+ ```ruby
588
+ tests = "#{__dir__}/**/*_test.rb"
589
+ loader.ignore(tests)
590
+ loader.setup
591
+ ```
592
+
593
+ <a id="markdown-edge-cases" name="edge-cases"></a>
594
+ ### Edge cases
595
+
596
+ A class or module that acts as a namespace:
597
+
598
+ ```ruby
599
+ # trip.rb
600
+ class Trip
601
+ include Geolocation
602
+ end
603
+
604
+ # trip/geolocation.rb
605
+ module Trip::Geolocation
606
+ ...
607
+ end
608
+ ```
609
+
610
+ has to be defined with the `class` or `module` keywords, as in the example above.
611
+
612
+ For technical reasons, raw constant assignment is not supported:
613
+
614
+ ```ruby
615
+ # trip.rb
616
+ Trip = Class.new { ... } # NOT SUPPORTED
617
+ Trip = Struct.new { ... } # NOT SUPPORTED
618
+ ```
619
+
620
+ This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
621
+
622
+ <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
623
+ ### Rules of thumb
624
+
625
+ 1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
626
+
627
+ 2. Think the mere existence of a file is effectively like writing a `require` call for them, which is executed on demand (autoload) or upfront (eager load).
628
+
629
+ 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.
630
+
631
+ 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.
632
+
633
+ 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.
634
+
635
+ 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.
636
+
637
+ <a id="markdown-autoloading-explicit-namespaces-and-debuggers" name="autoloading-explicit-namespaces-and-debuggers"></a>
638
+ ### Autoloading, explicit namespaces, and debuggers
639
+
640
+ 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`.
641
+
642
+ 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.
643
+
644
+ 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.
645
+
646
+ <a id="markdown-pronunciation" name="pronunciation"></a>
647
+ ## Pronunciation
648
+
649
+ "Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
650
+
651
+ <a id="markdown-supported-ruby-versions" name="supported-ruby-versions"></a>
652
+ ## Supported Ruby versions
653
+
654
+ Zeitwerk works with MRI 2.4.4 and above.
655
+
656
+ <a id="markdown-testing" name="testing"></a>
657
+ ## Testing
658
+
659
+ In order to run the test suite of Zeitwerk, `cd` into the project root and execute
660
+
661
+ ```
662
+ bin/test
663
+ ```
664
+
665
+ To run one particular suite, pass its file name as an argument:
666
+
667
+ ```
668
+ bin/test test/lib/zeitwerk/test_eager_load.rb
669
+ ```
670
+
671
+ 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`:
672
+
673
+ ```ruby
674
+ focus
675
+ test "capitalizes the first letter" do
676
+ assert_equal "User", camelize("user")
677
+ end
678
+ ```
679
+
680
+ and run `bin/test`.
681
+
682
+ <a id="markdown-motivation" name="motivation"></a>
683
+ ## Motivation
684
+
685
+ 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.
686
+
687
+ 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.
688
+
689
+ <a id="markdown-thanks" name="thanks"></a>
690
+ ## Thanks
691
+
692
+ I'd like to thank [@matthewd](https://github.com/matthewd) for the discussions we've had about this topic in the past years, I learned a couple of tricks used in Zeitwerk from him.
693
+
694
+ 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.
695
+
696
+ 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 ❤️.
697
+
698
+ 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. 💯
699
+
700
+ <a id="markdown-license" name="license"></a>
701
+ ## License
702
+
703
+ Released under the MIT License, Copyright (c) 2019–<i>ω</i> Xavier Noria.