zeitwerk 2.1.10
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/README.md +533 -0
- data/lib/zeitwerk.rb +12 -0
- data/lib/zeitwerk/error.rb +10 -0
- data/lib/zeitwerk/explicit_namespace.rb +80 -0
- data/lib/zeitwerk/gem_inflector.rb +19 -0
- data/lib/zeitwerk/inflector.rb +19 -0
- data/lib/zeitwerk/kernel.rb +33 -0
- data/lib/zeitwerk/loader.rb +759 -0
- data/lib/zeitwerk/loader/callbacks.rb +71 -0
- data/lib/zeitwerk/real_mod_name.rb +15 -0
- data/lib/zeitwerk/registry.rb +147 -0
- data/lib/zeitwerk/version.rb +5 -0
- metadata +58 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 3dbf7502d4126651ab645926f072af5f5164fcb495c06ae32e9748aa2807670e
|
4
|
+
data.tar.gz: e124bca82ed054d1ca304e95605ad011a2c6411792653c3c86b785a3cc956e06
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 7efe14aeb7e16563d6a1b69b2aac82d75dd1c4e79dae2fb4654e7c93742e15018f16fad4591f8763bf03b2f9d9d71a6e95209907a0765952dafa8dedc957d2ef
|
7
|
+
data.tar.gz: 8dea5ad3b1979cacb619b13385b337e81cc08efc39e0411f890229f0a9d17035fdfb17cf2ac84f6dcd3eeec4b4daa732e796e51fc1fdf707c210d9943481edcf
|
data/README.md
ADDED
@@ -0,0 +1,533 @@
|
|
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.svg?style=for-the-badge&branch=master)](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
|
+
- [Pronunciation](#pronunciation)
|
33
|
+
- [Supported Ruby versions](#supported-ruby-versions)
|
34
|
+
- [Motivation](#motivation)
|
35
|
+
- [Thanks](#thanks)
|
36
|
+
- [License](#license)
|
37
|
+
|
38
|
+
<!-- /TOC -->
|
39
|
+
|
40
|
+
<a id="markdown-introduction" name="introduction"></a>
|
41
|
+
## Introduction
|
42
|
+
|
43
|
+
Zeitwerk is an efficient and thread-safe code loader for Ruby.
|
44
|
+
|
45
|
+
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.
|
46
|
+
|
47
|
+
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.
|
48
|
+
|
49
|
+
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.
|
50
|
+
|
51
|
+
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.
|
52
|
+
|
53
|
+
<a id="markdown-synopsis" name="synopsis"></a>
|
54
|
+
## Synopsis
|
55
|
+
|
56
|
+
Main interface for gems:
|
57
|
+
|
58
|
+
```ruby
|
59
|
+
# lib/my_gem.rb (main file)
|
60
|
+
|
61
|
+
require "zeitwerk"
|
62
|
+
loader = Zeitwerk::Loader.for_gem
|
63
|
+
loader.setup # ready!
|
64
|
+
|
65
|
+
module MyGem
|
66
|
+
# ...
|
67
|
+
end
|
68
|
+
|
69
|
+
loader.eager_load # optionally
|
70
|
+
```
|
71
|
+
|
72
|
+
Main generic interface:
|
73
|
+
|
74
|
+
```ruby
|
75
|
+
loader = Zeitwerk::Loader.new
|
76
|
+
loader.push_dir(...)
|
77
|
+
loader.setup # ready!
|
78
|
+
```
|
79
|
+
|
80
|
+
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.
|
81
|
+
|
82
|
+
You can reload if you want to:
|
83
|
+
|
84
|
+
```ruby
|
85
|
+
loader = Zeitwerk::Loader.new
|
86
|
+
loader.push_dir(...)
|
87
|
+
loader.enable_reloading # you need to opt-in before setup
|
88
|
+
loader.setup
|
89
|
+
...
|
90
|
+
loader.reload
|
91
|
+
```
|
92
|
+
|
93
|
+
and you can eager load all the code:
|
94
|
+
|
95
|
+
```ruby
|
96
|
+
loader.eager_load
|
97
|
+
```
|
98
|
+
|
99
|
+
It is also possible to broadcast `eager_load` to all instances:
|
100
|
+
|
101
|
+
```ruby
|
102
|
+
Zeitwerk::Loader.eager_load_all
|
103
|
+
```
|
104
|
+
|
105
|
+
<a id="markdown-file-structure" name="file-structure"></a>
|
106
|
+
## File structure
|
107
|
+
|
108
|
+
To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
|
109
|
+
|
110
|
+
```
|
111
|
+
lib/my_gem.rb -> MyGem
|
112
|
+
lib/my_gem/foo.rb -> MyGem::Foo
|
113
|
+
lib/my_gem/bar_baz.rb -> MyGem::BarBaz
|
114
|
+
lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
|
115
|
+
```
|
116
|
+
|
117
|
+
Every directory configured with `push_dir` acts as root namespace. There can be several of them. For example, given
|
118
|
+
|
119
|
+
```ruby
|
120
|
+
loader.push_dir(Rails.root.join("app/models"))
|
121
|
+
loader.push_dir(Rails.root.join("app/controllers"))
|
122
|
+
```
|
123
|
+
|
124
|
+
Zeitwerk understands that their respective files and subdirectories belong to the root namespace:
|
125
|
+
|
126
|
+
```
|
127
|
+
app/models/user.rb -> User
|
128
|
+
app/controllers/admin/users_controller.rb -> Admin::UsersController
|
129
|
+
```
|
130
|
+
|
131
|
+
<a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
|
132
|
+
### Implicit namespaces
|
133
|
+
|
134
|
+
Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
|
135
|
+
|
136
|
+
```
|
137
|
+
app/controllers/admin/users_controller.rb -> Admin::UsersController
|
138
|
+
```
|
139
|
+
|
140
|
+
`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.
|
141
|
+
|
142
|
+
<a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
|
143
|
+
### Explicit namespaces
|
144
|
+
|
145
|
+
Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
|
146
|
+
|
147
|
+
```
|
148
|
+
app/models/hotel.rb -> Hotel
|
149
|
+
app/models/hotel/pricing.rb -> Hotel::Pricing
|
150
|
+
```
|
151
|
+
|
152
|
+
There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
|
153
|
+
|
154
|
+
The classes and modules from the namespace are already available in the body of the class or module defining it:
|
155
|
+
|
156
|
+
```ruby
|
157
|
+
class Hotel < ApplicationRecord
|
158
|
+
include Pricing # works
|
159
|
+
...
|
160
|
+
end
|
161
|
+
```
|
162
|
+
|
163
|
+
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.
|
164
|
+
|
165
|
+
<a id="markdown-nested-root-directories" name="nested-root-directories"></a>
|
166
|
+
### Nested root directories
|
167
|
+
|
168
|
+
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.
|
169
|
+
|
170
|
+
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:
|
171
|
+
|
172
|
+
```
|
173
|
+
app/models/concerns/geolocatable.rb
|
174
|
+
```
|
175
|
+
|
176
|
+
should define `Geolocatable`, not `Concerns::Geolocatable`.
|
177
|
+
|
178
|
+
<a id="markdown-usage" name="usage"></a>
|
179
|
+
## Usage
|
180
|
+
|
181
|
+
<a id="markdown-setup" name="setup"></a>
|
182
|
+
### Setup
|
183
|
+
|
184
|
+
Loaders are ready to load code right after calling `setup` on them:
|
185
|
+
|
186
|
+
```ruby
|
187
|
+
loader.setup
|
188
|
+
```
|
189
|
+
|
190
|
+
This method is synchronized and idempotent.
|
191
|
+
|
192
|
+
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:
|
193
|
+
|
194
|
+
```ruby
|
195
|
+
loader.push_dir(...)
|
196
|
+
loader.push_dir(...)
|
197
|
+
loader.setup
|
198
|
+
```
|
199
|
+
|
200
|
+
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.
|
201
|
+
|
202
|
+
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.
|
203
|
+
|
204
|
+
<a id="markdown-reloading" name="reloading"></a>
|
205
|
+
### Reloading
|
206
|
+
|
207
|
+
Zeitwerk is able to reload code, but you need to enable this feature:
|
208
|
+
|
209
|
+
```ruby
|
210
|
+
loader = Zeitwerk::Loader.new
|
211
|
+
loader.push_dir(...)
|
212
|
+
loader.enable_reloading # you need to opt-in before setup
|
213
|
+
loader.setup
|
214
|
+
...
|
215
|
+
loader.reload
|
216
|
+
```
|
217
|
+
|
218
|
+
There is no way to undo this, either you want to reload or you don't.
|
219
|
+
|
220
|
+
Enabling reloading after setup raises `Zeitwerk::Error`. Similarly, calling `reload` without having enabled reloading also raises `Zeitwerk::Error`.
|
221
|
+
|
222
|
+
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.
|
223
|
+
|
224
|
+
Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
|
225
|
+
|
226
|
+
It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
|
227
|
+
|
228
|
+
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.
|
229
|
+
|
230
|
+
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.
|
231
|
+
|
232
|
+
<a id="markdown-eager-loading" name="eager-loading"></a>
|
233
|
+
### Eager loading
|
234
|
+
|
235
|
+
Zeitwerk instances are able to eager load their managed files:
|
236
|
+
|
237
|
+
```ruby
|
238
|
+
loader.eager_load
|
239
|
+
```
|
240
|
+
|
241
|
+
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:
|
242
|
+
|
243
|
+
```ruby
|
244
|
+
db_adapters = "#{__dir__}/my_gem/db_adapters"
|
245
|
+
loader.do_not_eager_load(db_adapters)
|
246
|
+
loader.setup
|
247
|
+
loader.eager_load # won't eager load the database adapters
|
248
|
+
```
|
249
|
+
|
250
|
+
Eager loading is synchronized and idempotent.
|
251
|
+
|
252
|
+
If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
|
253
|
+
|
254
|
+
```ruby
|
255
|
+
Zeitwerk::Loader.eager_load_all
|
256
|
+
```
|
257
|
+
|
258
|
+
This may be handy in top-level services, like web applications.
|
259
|
+
|
260
|
+
Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
|
261
|
+
|
262
|
+
<a id="markdown-inflection" name="inflection"></a>
|
263
|
+
### Inflection
|
264
|
+
|
265
|
+
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.
|
266
|
+
|
267
|
+
<a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
|
268
|
+
#### Zeitwerk::Inflector
|
269
|
+
|
270
|
+
This is a very basic inflector that converts snake case to camel case:
|
271
|
+
|
272
|
+
```
|
273
|
+
user -> User
|
274
|
+
users_controller -> UsersController
|
275
|
+
html_parser -> HtmlParser
|
276
|
+
```
|
277
|
+
|
278
|
+
There are no inflection rules or global configuration that can affect this inflector. It is deterministic.
|
279
|
+
|
280
|
+
This is the default inflector.
|
281
|
+
|
282
|
+
<a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
|
283
|
+
#### Zeitwerk::GemInflector
|
284
|
+
|
285
|
+
The loader instantiated behind the scenes by `Zeitwerk::Loader.for_gem` gets assigned by default an inflector that is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
|
286
|
+
|
287
|
+
<a id="markdown-custom-inflector" name="custom-inflector"></a>
|
288
|
+
#### Custom inflector
|
289
|
+
|
290
|
+
The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
|
291
|
+
|
292
|
+
```ruby
|
293
|
+
# frozen_string_literal: true
|
294
|
+
|
295
|
+
class MyInflector < Zeitwerk::Inflector
|
296
|
+
def camelize(basename, _abspath)
|
297
|
+
case basename
|
298
|
+
when "api"
|
299
|
+
"API"
|
300
|
+
when "mysql_adapter"
|
301
|
+
"MySQLAdapter"
|
302
|
+
else
|
303
|
+
super
|
304
|
+
end
|
305
|
+
end
|
306
|
+
end
|
307
|
+
```
|
308
|
+
|
309
|
+
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.
|
310
|
+
|
311
|
+
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.
|
312
|
+
|
313
|
+
Then, assign the inflector:
|
314
|
+
|
315
|
+
```ruby
|
316
|
+
loader.inflector = MyInflector.new
|
317
|
+
```
|
318
|
+
|
319
|
+
This needs to be done before calling `setup`.
|
320
|
+
|
321
|
+
<a id="markdown-logging" name="logging"></a>
|
322
|
+
### Logging
|
323
|
+
|
324
|
+
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.
|
325
|
+
|
326
|
+
The `log!` method is a quick shortcut to let the loader log to `$stdout`:
|
327
|
+
|
328
|
+
```
|
329
|
+
loader.log!
|
330
|
+
```
|
331
|
+
|
332
|
+
If you want more control, a logger can be configured as a callable
|
333
|
+
|
334
|
+
```ruby
|
335
|
+
loader.logger = method(:puts)
|
336
|
+
loader.logger = ->(msg) { ... }
|
337
|
+
```
|
338
|
+
|
339
|
+
as well as anything that responds to `debug`:
|
340
|
+
|
341
|
+
```ruby
|
342
|
+
loader.logger = Logger.new($stderr)
|
343
|
+
loader.logger = Rails.logger
|
344
|
+
```
|
345
|
+
|
346
|
+
In both cases, the corresponding methods are going to be passed exactly one argument with the message to be logged.
|
347
|
+
|
348
|
+
It is also possible to set a global default this way:
|
349
|
+
|
350
|
+
```ruby
|
351
|
+
Zeitwerk::Loader.default_logger = method(:puts)
|
352
|
+
```
|
353
|
+
|
354
|
+
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.
|
355
|
+
|
356
|
+
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.
|
357
|
+
|
358
|
+
<a id="markdown-loader-tag" name="loader-tag"></a>
|
359
|
+
#### Loader tag
|
360
|
+
|
361
|
+
Loaders have a tag that is printed in traces in order to be able to distinguish them in globally logged activity:
|
362
|
+
|
363
|
+
```
|
364
|
+
Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
|
365
|
+
```
|
366
|
+
|
367
|
+
By default, a random tag like the one above is assigned, but you can change it:
|
368
|
+
|
369
|
+
```
|
370
|
+
loader.tag = "grep_me"
|
371
|
+
```
|
372
|
+
|
373
|
+
The tag of a loader returned by `for_gem` is the basename of the root file without extension:
|
374
|
+
|
375
|
+
```
|
376
|
+
Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
|
377
|
+
```
|
378
|
+
|
379
|
+
<a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
|
380
|
+
### Ignoring parts of the project
|
381
|
+
|
382
|
+
Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
|
383
|
+
|
384
|
+
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.
|
385
|
+
|
386
|
+
You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
|
387
|
+
|
388
|
+
Let's see some use cases.
|
389
|
+
|
390
|
+
<a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
|
391
|
+
#### Use case: Files that do not follow the conventions
|
392
|
+
|
393
|
+
Let's suppose that your gem decorates something in `Kernel`:
|
394
|
+
|
395
|
+
```ruby
|
396
|
+
# lib/my_gem/core_ext/kernel.rb
|
397
|
+
|
398
|
+
Kernel.module_eval do
|
399
|
+
# ...
|
400
|
+
end
|
401
|
+
```
|
402
|
+
|
403
|
+
That file does not define a constant path after the path name and you need to tell Zeitwerk:
|
404
|
+
|
405
|
+
```ruby
|
406
|
+
kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
|
407
|
+
loader.ignore(kernel_ext)
|
408
|
+
loader.setup
|
409
|
+
```
|
410
|
+
|
411
|
+
You can also ignore the whole directory:
|
412
|
+
|
413
|
+
```ruby
|
414
|
+
core_ext = "#{__dir__}/my_gem/core_ext"
|
415
|
+
loader.ignore(core_ext)
|
416
|
+
loader.setup
|
417
|
+
```
|
418
|
+
|
419
|
+
<a id="markdown-use-case-the-adapter-pattern" name="use-case-the-adapter-pattern"></a>
|
420
|
+
#### Use case: The adapter pattern
|
421
|
+
|
422
|
+
Another use case for ignoring files is the adapter pattern.
|
423
|
+
|
424
|
+
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:
|
425
|
+
|
426
|
+
```ruby
|
427
|
+
# my_gem/db_adapters/postgresql.rb
|
428
|
+
require "pg"
|
429
|
+
```
|
430
|
+
|
431
|
+
but you don't want your users to install them all, only the one they are going to use.
|
432
|
+
|
433
|
+
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:
|
434
|
+
|
435
|
+
```ruby
|
436
|
+
db_adapters = "#{__dir__}/my_gem/db_adapters"
|
437
|
+
loader.ignore(db_adapters)
|
438
|
+
loader.setup
|
439
|
+
```
|
440
|
+
|
441
|
+
The chosen adapter, then, has to be loaded by hand somehow:
|
442
|
+
|
443
|
+
```ruby
|
444
|
+
require "my_gem/db_adapters/#{config[:db_adapter]}"
|
445
|
+
```
|
446
|
+
|
447
|
+
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.
|
448
|
+
|
449
|
+
<a id="markdown-use-case-test-files-mixed-with-implementation-files" name="use-case-test-files-mixed-with-implementation-files"></a>
|
450
|
+
#### Use case: Test files mixed with implementation files
|
451
|
+
|
452
|
+
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:
|
453
|
+
|
454
|
+
```ruby
|
455
|
+
tests = "#{__dir__}/**/*_test.rb"
|
456
|
+
loader.ignore(tests)
|
457
|
+
loader.setup
|
458
|
+
```
|
459
|
+
|
460
|
+
<a id="markdown-edge-cases" name="edge-cases"></a>
|
461
|
+
### Edge cases
|
462
|
+
|
463
|
+
A class or module that acts as a namespace:
|
464
|
+
|
465
|
+
```ruby
|
466
|
+
# trip.rb
|
467
|
+
class Trip
|
468
|
+
include Geolocation
|
469
|
+
end
|
470
|
+
|
471
|
+
# trip/geolocation.rb
|
472
|
+
module Trip::Geolocation
|
473
|
+
...
|
474
|
+
end
|
475
|
+
```
|
476
|
+
|
477
|
+
has to be defined with the `class` or `module` keywords, as in the example above.
|
478
|
+
|
479
|
+
For technical reasons, raw constant assignment is not supported:
|
480
|
+
|
481
|
+
```ruby
|
482
|
+
# trip.rb
|
483
|
+
Trip = Class.new { ... } # NOT SUPPORTED
|
484
|
+
Trip = Struct.new { ... } # NOT SUPPORTED
|
485
|
+
```
|
486
|
+
|
487
|
+
This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
|
488
|
+
|
489
|
+
<a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
|
490
|
+
### Rules of thumb
|
491
|
+
|
492
|
+
1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
|
493
|
+
|
494
|
+
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).
|
495
|
+
|
496
|
+
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.
|
497
|
+
|
498
|
+
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.
|
499
|
+
|
500
|
+
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.
|
501
|
+
|
502
|
+
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.
|
503
|
+
|
504
|
+
<a id="markdown-pronunciation" name="pronunciation"></a>
|
505
|
+
## Pronunciation
|
506
|
+
|
507
|
+
"Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
|
508
|
+
|
509
|
+
<a id="markdown-supported-ruby-versions" name="supported-ruby-versions"></a>
|
510
|
+
## Supported Ruby versions
|
511
|
+
|
512
|
+
Zeitwerk works with MRI 2.4.4 and above.
|
513
|
+
|
514
|
+
<a id="markdown-motivation" name="motivation"></a>
|
515
|
+
## Motivation
|
516
|
+
|
517
|
+
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.
|
518
|
+
|
519
|
+
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.
|
520
|
+
|
521
|
+
<a id="markdown-thanks" name="thanks"></a>
|
522
|
+
## Thanks
|
523
|
+
|
524
|
+
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.
|
525
|
+
|
526
|
+
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.
|
527
|
+
|
528
|
+
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. 💯
|
529
|
+
|
530
|
+
<a id="markdown-license" name="license"></a>
|
531
|
+
## License
|
532
|
+
|
533
|
+
Released under the MIT License, Copyright (c) 2019–<i>ω</i> Xavier Noria.
|