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