zeitwerk 2.2.1

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: b7d5a0f54405ad45dd6afc9bf54bde579f66a75fb142cdbbfb5476157dd75493
4
+ data.tar.gz: b81311bb19c3b699a6720a3bb3d6df503b858a439c5f1f2605e029117de36bcb
5
+ SHA512:
6
+ metadata.gz: 4f6fd6e8f7bd479ca6935d1f57d065151aff3be6977ad068f6b4ecdce200bbd131f4db4f2cc1bc2a719cb332b538cf24be55eb936a51572ac5c06676d21763f2
7
+ data.tar.gz: d4266c65e380b356ff4df7394f2f1882f72ac32b5226dedd717f6b4064c8ac1b8fd3d70ec08b6f9838debfc3690d2f3eee2d6885e446f087a686a619c872c718
@@ -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,650 @@
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
+ - [Nested root directories](#nested-root-directories)
16
+ - [Usage](#usage)
17
+ - [Setup](#setup)
18
+ - [Reloading](#reloading)
19
+ - [Eager loading](#eager-loading)
20
+ - [Inflection](#inflection)
21
+ - [Zeitwerk::Inflector](#zeitwerkinflector)
22
+ - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
23
+ - [Custom inflector](#custom-inflector)
24
+ - [Logging](#logging)
25
+ - [Loader tag](#loader-tag)
26
+ - [Ignoring parts of the project](#ignoring-parts-of-the-project)
27
+ - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
28
+ - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
29
+ - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
30
+ - [Edge cases](#edge-cases)
31
+ - [Rules of thumb](#rules-of-thumb)
32
+ - [Autoloading, explicit namespaces, and debuggers](#autoloading-explicit-namespaces-and-debuggers)
33
+ - [Pronunciation](#pronunciation)
34
+ - [Supported Ruby versions](#supported-ruby-versions)
35
+ - [Testing](#testing)
36
+ - [Motivation](#motivation)
37
+ - [Thanks](#thanks)
38
+ - [License](#license)
39
+
40
+ <!-- /TOC -->
41
+
42
+ <a id="markdown-introduction" name="introduction"></a>
43
+ ## Introduction
44
+
45
+ Zeitwerk is an efficient and thread-safe code loader for Ruby.
46
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ 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
+
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.
54
+
55
+ <a id="markdown-synopsis" name="synopsis"></a>
56
+ ## Synopsis
57
+
58
+ Main interface for gems:
59
+
60
+ ```ruby
61
+ # lib/my_gem.rb (main file)
62
+
63
+ require "zeitwerk"
64
+ loader = Zeitwerk::Loader.for_gem
65
+ loader.setup # ready!
66
+
67
+ module MyGem
68
+ # ...
69
+ end
70
+
71
+ loader.eager_load # optionally
72
+ ```
73
+
74
+ Main generic interface:
75
+
76
+ ```ruby
77
+ loader = Zeitwerk::Loader.new
78
+ loader.push_dir(...)
79
+ loader.setup # ready!
80
+ ```
81
+
82
+ 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.
83
+
84
+ You can reload if you want to:
85
+
86
+ ```ruby
87
+ loader = Zeitwerk::Loader.new
88
+ loader.push_dir(...)
89
+ loader.enable_reloading # you need to opt-in before setup
90
+ loader.setup
91
+ ...
92
+ loader.reload
93
+ ```
94
+
95
+ and you can eager load all the code:
96
+
97
+ ```ruby
98
+ loader.eager_load
99
+ ```
100
+
101
+ It is also possible to broadcast `eager_load` to all instances:
102
+
103
+ ```ruby
104
+ Zeitwerk::Loader.eager_load_all
105
+ ```
106
+
107
+ <a id="markdown-file-structure" name="file-structure"></a>
108
+ ## File structure
109
+
110
+ To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
111
+
112
+ ```
113
+ lib/my_gem.rb -> MyGem
114
+ lib/my_gem/foo.rb -> MyGem::Foo
115
+ lib/my_gem/bar_baz.rb -> MyGem::BarBaz
116
+ lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
117
+ ```
118
+
119
+ Every directory configured with `push_dir` acts as root namespace. There can be several of them. For example, given
120
+
121
+ ```ruby
122
+ loader.push_dir(Rails.root.join("app/models"))
123
+ loader.push_dir(Rails.root.join("app/controllers"))
124
+ ```
125
+
126
+ Zeitwerk understands that their respective files and subdirectories belong to the root namespace:
127
+
128
+ ```
129
+ app/models/user.rb -> User
130
+ app/controllers/admin/users_controller.rb -> Admin::UsersController
131
+ ```
132
+
133
+ <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
134
+ ### Implicit namespaces
135
+
136
+ Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
137
+
138
+ ```
139
+ app/controllers/admin/users_controller.rb -> Admin::UsersController
140
+ ```
141
+
142
+ `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.
143
+
144
+ <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
145
+ ### Explicit namespaces
146
+
147
+ Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
148
+
149
+ ```
150
+ app/models/hotel.rb -> Hotel
151
+ app/models/hotel/pricing.rb -> Hotel::Pricing
152
+ ```
153
+
154
+ There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
155
+
156
+ The classes and modules from the namespace are already available in the body of the class or module defining it:
157
+
158
+ ```ruby
159
+ class Hotel < ApplicationRecord
160
+ include Pricing # works
161
+ ...
162
+ end
163
+ ```
164
+
165
+ 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
+
167
+ <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
168
+ ### Nested root directories
169
+
170
+ 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.
171
+
172
+ 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:
173
+
174
+ ```
175
+ app/models/concerns/geolocatable.rb
176
+ ```
177
+
178
+ should define `Geolocatable`, not `Concerns::Geolocatable`.
179
+
180
+ <a id="markdown-usage" name="usage"></a>
181
+ ## Usage
182
+
183
+ <a id="markdown-setup" name="setup"></a>
184
+ ### Setup
185
+
186
+ Loaders are ready to load code right after calling `setup` on them:
187
+
188
+ ```ruby
189
+ loader.setup
190
+ ```
191
+
192
+ This method is synchronized and idempotent.
193
+
194
+ 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:
195
+
196
+ ```ruby
197
+ loader.push_dir(...)
198
+ loader.push_dir(...)
199
+ loader.setup
200
+ ```
201
+
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.
203
+
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:
205
+
206
+ ```ruby
207
+ # lib/my_gem.rb (main file)
208
+
209
+ require "zeitwerk"
210
+ loader = Zeitwerk::Loader.for_gem
211
+ loader.setup
212
+
213
+ module MyGem
214
+ # Since the setup has been performed, at this point we are already able
215
+ # to reference project constants, in this case MyGem::MyLogger.
216
+ include MyLogger
217
+ end
218
+ ```
219
+
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.
221
+
222
+ <a id="markdown-reloading" name="reloading"></a>
223
+ ### Reloading
224
+
225
+ Zeitwerk is able to reload code, but you need to enable this feature:
226
+
227
+ ```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.
241
+
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.
243
+
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.
245
+
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.
247
+
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.
249
+
250
+ <a id="markdown-eager-loading" name="eager-loading"></a>
251
+ ### Eager loading
252
+
253
+ Zeitwerk instances are able to eager load their managed files:
254
+
255
+ ```ruby
256
+ loader.eager_load
257
+ ```
258
+
259
+ 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:
260
+
261
+ ```ruby
262
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
263
+ loader.do_not_eager_load(db_adapters)
264
+ loader.setup
265
+ loader.eager_load # won't eager load the database adapters
266
+ ```
267
+
268
+ 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).
269
+
270
+ Eager loading is synchronized and idempotent.
271
+
272
+ If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
273
+
274
+ ```ruby
275
+ Zeitwerk::Loader.eager_load_all
276
+ ```
277
+
278
+ This may be handy in top-level services, like web applications.
279
+
280
+ Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
281
+
282
+ <a id="markdown-inflection" name="inflection"></a>
283
+ ### Inflection
284
+
285
+ 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.
286
+
287
+ <a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
288
+ #### Zeitwerk::Inflector
289
+
290
+ This is a very basic inflector that converts snake case to camel case:
291
+
292
+ ```
293
+ user -> User
294
+ users_controller -> UsersController
295
+ html_parser -> HtmlParser
296
+ ```
297
+
298
+ The camelize logic can be overridden easily for individual basenames:
299
+
300
+ ```ruby
301
+ loader.inflector.inflect(
302
+ "html_parser" => "HTMLParser",
303
+ "mysql_adapter" => "MySQLAdapter"
304
+ )
305
+ ```
306
+
307
+ The `inflect` method can be invoked several times if you prefer this other style:
308
+
309
+ ```ruby
310
+ loader.inflector.inflect "html_parser" => "HTMLParser"
311
+ loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
312
+ ```
313
+
314
+ Overrides need to be configured before calling `setup`.
315
+
316
+ There are no inflection rules or global configuration that can affect this inflector. It is deterministic.
317
+
318
+ Loaders instantiated with `Zeitwerk::Loader.new` have an inflector of this type, independent of each other.
319
+
320
+ <a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
321
+ #### Zeitwerk::GemInflector
322
+
323
+ This inflector is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
324
+
325
+ Loaders instantiated with `Zeitwerk::Loader.for_gem` have an inflector of this type, independent of each other.
326
+
327
+ <a id="markdown-custom-inflector" name="custom-inflector"></a>
328
+ #### Custom inflector
329
+
330
+ The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
331
+
332
+ ```ruby
333
+ # frozen_string_literal: true
334
+
335
+ class MyInflector < Zeitwerk::Inflector
336
+ def camelize(basename, abspath)
337
+ if basename =~ /\Ahtml_(.*)/
338
+ "HTML" + super($1, abspath)
339
+ else
340
+ super
341
+ end
342
+ end
343
+ end
344
+ ```
345
+
346
+ 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.
347
+
348
+ 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.
349
+
350
+ Then, assign the inflector:
351
+
352
+ ```ruby
353
+ loader.inflector = MyInflector.new
354
+ ```
355
+
356
+ This needs to be done before calling `setup`.
357
+
358
+ 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:
359
+
360
+ ```ruby
361
+ # lib/my_gem/inflector.rb
362
+ module MyGem
363
+ class Inflector < Zeitwerk::GemInflector
364
+ ...
365
+ end
366
+ end
367
+
368
+ # lib/my_gem.rb
369
+ require "zeitwerk"
370
+ require_relative "my_gem/inflector"
371
+
372
+ loader = Zeitwerk::Loader.for_gem
373
+ loader.inflector = MyGem::Inflector.new(__FILE__)
374
+ loader.setup
375
+
376
+ module MyGem
377
+ # ...
378
+ end
379
+ ```
380
+
381
+ Since `MyGem` is referenced before the namespace is defined in the main file, it is important to use this style:
382
+
383
+ ```ruby
384
+ # Correct, effectively defines MyGem.
385
+ module MyGem
386
+ class Inflector < Zeitwerk::GemInflector
387
+ # ...
388
+ end
389
+ end
390
+ ```
391
+
392
+ instead of:
393
+
394
+ ```ruby
395
+ # Raises uninitialized constant MyGem (NameError).
396
+ class MyGem::Inflector < Zeitwerk::GemInflector
397
+ # ...
398
+ end
399
+ ```
400
+
401
+ <a id="markdown-logging" name="logging"></a>
402
+ ### Logging
403
+
404
+ 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.
405
+
406
+ The `log!` method is a quick shortcut to let the loader log to `$stdout`:
407
+
408
+ ```
409
+ loader.log!
410
+ ```
411
+
412
+ If you want more control, a logger can be configured as a callable
413
+
414
+ ```ruby
415
+ loader.logger = method(:puts)
416
+ loader.logger = ->(msg) { ... }
417
+ ```
418
+
419
+ as well as anything that responds to `debug`:
420
+
421
+ ```ruby
422
+ loader.logger = Logger.new($stderr)
423
+ loader.logger = Rails.logger
424
+ ```
425
+
426
+ In both cases, the corresponding methods are going to be passed exactly one argument with the message to be logged.
427
+
428
+ It is also possible to set a global default this way:
429
+
430
+ ```ruby
431
+ Zeitwerk::Loader.default_logger = method(:puts)
432
+ ```
433
+
434
+ 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.
435
+
436
+ 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.
437
+
438
+ <a id="markdown-loader-tag" name="loader-tag"></a>
439
+ #### Loader tag
440
+
441
+ Loaders have a tag that is printed in traces in order to be able to distinguish them in globally logged activity:
442
+
443
+ ```
444
+ Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
445
+ ```
446
+
447
+ By default, a random tag like the one above is assigned, but you can change it:
448
+
449
+ ```
450
+ loader.tag = "grep_me"
451
+ ```
452
+
453
+ The tag of a loader returned by `for_gem` is the basename of the root file without extension:
454
+
455
+ ```
456
+ Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
457
+ ```
458
+
459
+ <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
460
+ ### Ignoring parts of the project
461
+
462
+ Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
463
+
464
+ 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.
465
+
466
+ You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
467
+
468
+ Let's see some use cases.
469
+
470
+ <a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
471
+ #### Use case: Files that do not follow the conventions
472
+
473
+ Let's suppose that your gem decorates something in `Kernel`:
474
+
475
+ ```ruby
476
+ # lib/my_gem/core_ext/kernel.rb
477
+
478
+ Kernel.module_eval do
479
+ # ...
480
+ end
481
+ ```
482
+
483
+ That file does not define a constant path after the path name and you need to tell Zeitwerk:
484
+
485
+ ```ruby
486
+ kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
487
+ loader.ignore(kernel_ext)
488
+ loader.setup
489
+ ```
490
+
491
+ You can also ignore the whole directory:
492
+
493
+ ```ruby
494
+ core_ext = "#{__dir__}/my_gem/core_ext"
495
+ loader.ignore(core_ext)
496
+ loader.setup
497
+ ```
498
+
499
+ <a id="markdown-use-case-the-adapter-pattern" name="use-case-the-adapter-pattern"></a>
500
+ #### Use case: The adapter pattern
501
+
502
+ Another use case for ignoring files is the adapter pattern.
503
+
504
+ 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:
505
+
506
+ ```ruby
507
+ # my_gem/db_adapters/postgresql.rb
508
+ require "pg"
509
+ ```
510
+
511
+ but you don't want your users to install them all, only the one they are going to use.
512
+
513
+ 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:
514
+
515
+ ```ruby
516
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
517
+ loader.ignore(db_adapters)
518
+ loader.setup
519
+ ```
520
+
521
+ The chosen adapter, then, has to be loaded by hand somehow:
522
+
523
+ ```ruby
524
+ require "my_gem/db_adapters/#{config[:db_adapter]}"
525
+ ```
526
+
527
+ 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.
528
+
529
+ <a id="markdown-use-case-test-files-mixed-with-implementation-files" name="use-case-test-files-mixed-with-implementation-files"></a>
530
+ #### Use case: Test files mixed with implementation files
531
+
532
+ 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:
533
+
534
+ ```ruby
535
+ tests = "#{__dir__}/**/*_test.rb"
536
+ loader.ignore(tests)
537
+ loader.setup
538
+ ```
539
+
540
+ <a id="markdown-edge-cases" name="edge-cases"></a>
541
+ ### Edge cases
542
+
543
+ A class or module that acts as a namespace:
544
+
545
+ ```ruby
546
+ # trip.rb
547
+ class Trip
548
+ include Geolocation
549
+ end
550
+
551
+ # trip/geolocation.rb
552
+ module Trip::Geolocation
553
+ ...
554
+ end
555
+ ```
556
+
557
+ has to be defined with the `class` or `module` keywords, as in the example above.
558
+
559
+ For technical reasons, raw constant assignment is not supported:
560
+
561
+ ```ruby
562
+ # trip.rb
563
+ Trip = Class.new { ... } # NOT SUPPORTED
564
+ Trip = Struct.new { ... } # NOT SUPPORTED
565
+ ```
566
+
567
+ This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
568
+
569
+ <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
570
+ ### Rules of thumb
571
+
572
+ 1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
573
+
574
+ 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).
575
+
576
+ 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.
577
+
578
+ 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.
579
+
580
+ 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.
581
+
582
+ 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
+
584
+ <a id="markdown-autoloading-explicit-namespaces-and-debuggers" name="autoloading-explicit-namespaces-and-debuggers"></a>
585
+ ### Autoloading, explicit namespaces, and debuggers
586
+
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`.
588
+
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.
590
+
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.
592
+
593
+ <a id="markdown-pronunciation" name="pronunciation"></a>
594
+ ## Pronunciation
595
+
596
+ "Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
597
+
598
+ <a id="markdown-supported-ruby-versions" name="supported-ruby-versions"></a>
599
+ ## Supported Ruby versions
600
+
601
+ Zeitwerk works with MRI 2.4.4 and above.
602
+
603
+ <a id="markdown-testing" name="testing"></a>
604
+ ## Testing
605
+
606
+ In order to run the test suite of Zeitwerk, `cd` into the project root and execute
607
+
608
+ ```
609
+ bin/test
610
+ ```
611
+
612
+ To run one particular suite, pass its file name as an argument:
613
+
614
+ ```
615
+ bin/test test/lib/zeitwerk/test_eager_load.rb
616
+ ```
617
+
618
+ 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`:
619
+
620
+ ```ruby
621
+ focus
622
+ test "capitalizes the first letter" do
623
+ assert_equal "User", camelize("user")
624
+ end
625
+ ```
626
+
627
+ and run `bin/test`.
628
+
629
+ <a id="markdown-motivation" name="motivation"></a>
630
+ ## Motivation
631
+
632
+ 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.
633
+
634
+ 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.
635
+
636
+ <a id="markdown-thanks" name="thanks"></a>
637
+ ## Thanks
638
+
639
+ 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.
640
+
641
+ 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.
642
+
643
+ 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 ❤️.
644
+
645
+ 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. 💯
646
+
647
+ <a id="markdown-license" name="license"></a>
648
+ ## License
649
+
650
+ Released under the MIT License, Copyright (c) 2019–<i>ω</i> Xavier Noria.