opal-zeitwerk 0.2.3 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
data/README.md CHANGED
@@ -1,466 +1,1073 @@
1
- # Opal Zeitwerk
2
-
3
- ## Community and Support
4
- At the [Isomorfeus Project](http://isomorfeus.com) - isomorphic full stack Ruby for the web.
5
-
6
- ## TOC
7
- <!-- TOC -->
8
-
9
- - [Introduction](#introduction)
10
- - [Synopsis](#synopsis)
11
- - [File structure](#file-structure)
12
- - [Implicit namespaces](#implicit-namespaces)
13
- - [Explicit namespaces](#explicit-namespaces)
14
- - [Nested root directories](#nested-root-directories)
15
- - [Usage](#usage)
16
- - [Setup](#setup)
17
- - [Autoloading](#autoloading)
18
- - [Eager loading](#eager-loading)
19
- - [Reloading](#reloading)
20
- - [Inflection](#inflection)
21
- - [Zeitwerk::Inflector](#zeitwerkinflector)
22
- - [Custom inflector](#custom-inflector)
23
- - [Ignoring parts of the project](#ignoring-parts-of-the-project)
24
- - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
25
- - [Edge cases](#edge-cases)
26
- - [Rules of thumb](#rules-of-thumb)
27
- - [Autoloading, explicit namespaces, and debuggers](#autoloading-explicit-namespaces-and-debuggers)
28
- - [Pronunciation](#pronunciation)
29
- - [Supported Opal versions](#supported-opal-versions)
30
- - [Motivation](#motivation)
31
- - [License](#license)
32
-
33
- <!-- /TOC -->
34
-
35
- <a id="markdown-introduction" name="introduction"></a>
36
- ## Introduction
37
-
38
- Opal Zeitwerk is a port of the Ruby [Zeitwerk](https://github.com/fxn/zeitwerk) loader to Opal for autoloading ruby code in the Browser.
39
- Autoloading reduces upfront TTI(time to interactive) for large opal projects vastly.
40
-
41
- Given a [conventional file structure](#file-structure), Opal Zeitwerk is able to load your project's classes and modules on demand (autoloading),
42
- or upfront (eager loading)(currently untested). You don't need to write `require` calls for your own files, rather, you can streamline your programming,
43
- knowing that your classes and modules are available everywhere. This feature is efficient, and matches Ruby's semantics for constants.
44
-
45
- The gem is designed so that any project, gem dependency, application, etc. can have their own independent loader, managing their own project trees,
46
- and independent of each other. Each loader has its own configuration, inflector, and optional logger.
47
-
48
- Internally, Opal Zeitwerk issues `require` calls exclusively using absolute path names as recorded in Opal modules registry.
49
-
50
- Differences to Ruby Zeitwerk:
51
- - no logging (to keep asset size small and performance high)
52
- - no gem specific support: GemInflector, for_gem, etc.
53
-
54
- These don't make so much sense, as Opal Zeitwerk works on the global Opal.modules registry in the Browser, not the filesystem.
55
- - Zeitwerk::Loader.set_autoloads_in_dir is public, so it can be called from lazy loaded code, after updating Opal.modules.
56
- - There are no threads in javascript so thread support has been removed.
57
- - Tests don't run yet.
58
- <a id="markdown-synopsis" name="synopsis"></a>
59
- ## Synopsis
60
-
61
- Main generic interface:
62
-
63
- ```ruby
64
- loader = Zeitwerk::Loader.new
65
- loader.push_dir(...)
66
- loader.setup # ready!
67
- ```
68
-
69
- 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.
70
-
71
- You can reload if you want to:
72
-
73
- ```ruby
74
- loader = Zeitwerk::Loader.new
75
- loader.push_dir(...)
76
- loader.enable_reloading # you need to opt-in before setup
77
- loader.setup
78
- ...
79
- loader.reload
80
- ```
81
-
82
- and you can eager load all the code:
83
-
84
- ```ruby
85
- loader.eager_load
86
- ```
87
-
88
- It is also possible to broadcast `eager_load` to all instances:
89
-
90
- ```ruby
91
- Zeitwerk::Loader.eager_load_all
92
- ```
93
-
94
- <a id="markdown-file-structure" name="file-structure"></a>
95
- ## File structure
96
-
97
- To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
98
-
99
- ```
100
- lib/my_gem.rb -> 'my_gem' -> MyGem
101
- lib/my_gem/foo.rb -> 'my_gem/foo' -> MyGem::Foo
102
- lib/my_gem/bar_baz.rb -> 'my_gem/bar_baz' -> MyGem::BarBaz
103
- lib/my_gem/woo/zoo.rb -> 'my_gem/woo/zoo' -> MyGem::Woo::Zoo
104
- ```
105
- Second column shows how files are registered in Opals modules registry. These paths in the registry are relevant for Opal Zeitwerk running in the Browser.
106
- Every directory configured with `push_dir` acts as root namespace. There can be several of them. For example, given
107
-
108
- ```ruby
109
- loader.push_dir("app/models")
110
- loader.push_dir("app/controllers")
111
- ```
112
-
113
- Zeitwerk understands that their respective files and subdirectories belong to the root namespace:
114
-
115
- ```
116
- app/models/user -> User
117
- app/controllers/admin/users_controller -> Admin::UsersController
118
- ```
119
-
120
- <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
121
- ### Implicit namespaces
122
-
123
- Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
124
-
125
- ```
126
- app/controllers/admin/users_controller -> Admin::UsersController
127
- ```
128
-
129
- `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.
130
-
131
- <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
132
- ### Explicit namespaces
133
-
134
- Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
135
-
136
- ```
137
- app/models/hotel -> Hotel
138
- app/models/hotel/pricing -> Hotel::Pricing
139
- ```
140
-
141
- There, `app/models/hotel` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
142
-
143
- The classes and modules from the namespace are already available in the body of the class or module defining it:
144
-
145
- ```ruby
146
- class Hotel < ApplicationRecord
147
- include Pricing # works
148
- ...
149
- end
150
- ```
151
-
152
- 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.
153
-
154
- <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
155
- ### Nested root directories
156
-
157
- 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.
158
-
159
- 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:
160
-
161
- ```
162
- app/models/concerns/geolocatable
163
- ```
164
-
165
- should define `Geolocatable`, not `Concerns::Geolocatable`.
166
-
167
- <a id="markdown-usage" name="usage"></a>
168
- ## Usage
169
-
170
- Add to the Gemfile:
171
- ```
172
- gem 'opal', '>= 1.3.0'
173
- gem 'opal-zeitwerk', '~> 0.0.1'
174
- ```
175
-
176
- And to your loader of opal code:
177
- ```
178
- require 'zeitwerk'
179
- ```
180
-
181
- <a id="markdown-setup" name="setup"></a>
182
- ### Setup
183
- Files must be included in the compiled asset by:
184
- ```
185
- require_tree 'some_dir', autoload: true
186
- ```
187
- And added to the loader by:
188
- ```
189
- loader.push_dir('some_dir')
190
- ```
191
- The loader here requires the part of the path as it would appear in Opal.modules.
192
- If `require_tree` is called from a sub directory, the path from the root as it would appear in Opal.modules has to be prepended for push_dir.
193
-
194
- Loaders are ready to load code right after calling `setup` on them:
195
-
196
- ```ruby
197
- loader.setup
198
- ```
199
-
200
- This method is synchronized and idempotent.
201
-
202
- Customization should generally be done before that call. In particular, in the generic interface you may set the root module paths from which you want to load files:
203
-
204
- ```ruby
205
- loader.push_dir(...)
206
- loader.push_dir(...)
207
- loader.setup
208
- ```
209
-
210
- Zeitwerk works internally only with absolute paths.
211
-
212
- <a id="markdown-autoloading" name="autoloading"></a>
213
- ### Autoloading
214
-
215
- After `setup`, you are able to reference classes and modules from the project without issuing `require` calls for them. They are all available everywhere,
216
- 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.
217
-
218
- If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
219
-
220
- <a id="markdown-eager-loading" name="eager-loading"></a>
221
- ### Eager loading (untested)
222
-
223
- Zeitwerk instances are able to eager load their managed files:
224
-
225
- ```ruby
226
- loader.eager_load
227
- ```
228
-
229
- 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:
230
-
231
- ```ruby
232
- db_adapters = "#{__dir__}/my_gem/db_adapters"
233
- loader.do_not_eager_load(db_adapters)
234
- loader.setup
235
- loader.eager_load # won't eager load the database adapters
236
- ```
237
-
238
- Eager loading is synchronized and idempotent.
239
-
240
- If eager loading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
241
-
242
- If you want to eager load yourself and all dependencies using Zeitwerk, you can broadcast the `eager_load` call to all instances:
243
-
244
- ```ruby
245
- Zeitwerk::Loader.eager_load_all
246
- ```
247
-
248
- This may be handy in top-level services, like web applications.
249
-
250
- Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
251
-
252
- <a id="markdown-reloading" name="reloading"></a>
253
- ### Reloading (untested)
254
-
255
- Zeitwerk is able to reload code, but you need to enable this feature:
256
-
257
- ```ruby
258
- loader = Zeitwerk::Loader.new
259
- loader.push_dir(...)
260
- loader.enable_reloading # you need to opt-in before setup
261
- loader.setup
262
- ...
263
- loader.reload
264
- ```
265
-
266
- There is no way to undo this, either you want to reload or you don't.
267
-
268
- Enabling reloading after setup raises `Zeitwerk::Error`. Attempting to reload without having it enabled raises `Zeitwerk::ReloadingDisabledError`.
269
-
270
- 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.
271
-
272
- Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
273
-
274
- It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
275
-
276
- 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.
277
-
278
- 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.
279
-
280
- <a id="markdown-inflection" name="inflection"></a>
281
- ### Inflection
282
-
283
- 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.
284
-
285
- <a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
286
- #### Zeitwerk::Inflector
287
-
288
- This is a very basic inflector that converts snake case to camel case:
289
-
290
- ```
291
- user -> User
292
- users_controller -> UsersController
293
- html_parser -> HtmlParser
294
- ```
295
-
296
- The camelize logic can be overridden easily for individual basenames:
297
-
298
- ```ruby
299
- loader.inflector.inflect(
300
- "html_parser" => "HTMLParser",
301
- "mysql_adapter" => "MySQLAdapter"
302
- )
303
- ```
304
-
305
- The `inflect` method can be invoked several times if you prefer this other style:
306
-
307
- ```ruby
308
- loader.inflector.inflect "html_parser" => "HTMLParser"
309
- loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
310
- ```
311
-
312
- Overrides need to be configured before calling `setup`.
313
-
314
- There are no inflection rules or global configuration that can affect this inflector. It is deterministic.
315
-
316
- Loaders instantiated with `Zeitwerk::Loader.new` have an inflector of this type, independent of each other.
317
-
318
- <a id="markdown-custom-inflector" name="custom-inflector"></a>
319
- #### Custom inflector
320
-
321
- The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
322
-
323
- ```ruby
324
- # frozen_string_literal: true
325
-
326
- class MyInflector < Zeitwerk::Inflector
327
- def camelize(basename, abspath)
328
- if basename =~ /\Ahtml_(.*)/
329
- "HTML" + super($1, abspath)
330
- else
331
- super
332
- end
333
- end
334
- end
335
- ```
336
-
337
- 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.
338
-
339
- 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.
340
-
341
- Then, assign the inflector:
342
-
343
- ```ruby
344
- loader.inflector = MyInflector.new
345
- ```
346
-
347
- This needs to be done before calling `setup`.
348
-
349
- <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
350
- ### Ignoring parts of the project
351
-
352
- Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
353
-
354
- 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.
355
-
356
- You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
357
-
358
- Let's see some use cases.
359
-
360
- <a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
361
- #### Use case: Files that do not follow the conventions
362
-
363
- Let's suppose that your gem decorates something in `Kernel`:
364
-
365
- ```ruby
366
- # lib/my_gem/core_ext/kernel.rb
367
-
368
- Kernel.module_eval do
369
- # ...
370
- end
371
- ```
372
-
373
- That file does not define a constant path after the path name and you need to tell Zeitwerk:
374
-
375
- ```ruby
376
- kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
377
- loader.ignore(kernel_ext)
378
- loader.setup
379
- ```
380
-
381
- You can also ignore the whole directory:
382
-
383
- ```ruby
384
- core_ext = "#{__dir__}/my_gem/core_ext"
385
- loader.ignore(core_ext)
386
- loader.setup
387
- ```
388
-
389
- <a id="markdown-edge-cases" name="edge-cases"></a>
390
- ### Edge cases
391
-
392
- A class or module that acts as a namespace:
393
-
394
- ```ruby
395
- # trip.rb
396
- class Trip
397
- include Geolocation
398
- end
399
-
400
- # trip/geolocation.rb
401
- module Trip::Geolocation
402
- ...
403
- end
404
- ```
405
-
406
- has to be defined with the `class` or `module` keywords, as in the example above.
407
-
408
- For technical reasons, raw constant assignment is not supported:
409
-
410
- ```ruby
411
- # trip.rb
412
- Trip = Class.new { ... } # NOT SUPPORTED
413
- Trip = Struct.new { ... } # NOT SUPPORTED
414
- ```
415
-
416
- This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
417
-
418
- <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
419
- ### Rules of thumb
420
-
421
- 1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
422
-
423
- 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).
424
-
425
- 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.
426
-
427
- 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.
428
-
429
- 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.
430
-
431
- 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.
432
-
433
- <a id="markdown-autoloading-explicit-namespaces-and-debuggers" name="autoloading-explicit-namespaces-and-debuggers"></a>
434
- ### Autoloading, explicit namespaces, and debuggers
435
-
436
- 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`.
437
-
438
- 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.
439
-
440
- 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.
441
-
442
- <a id="markdown-pronunciation" name="pronunciation"></a>
443
- ## Pronunciation
444
-
445
- "Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
446
-
447
- <a id="markdown-supported-opal-versions" name="supported-opal-versions"></a>
448
- ## Supported Opal versions
449
-
450
- Opal Zeitwerk currently works with Opal releases >= 1.3.0. For the Gemfile:
451
- ```
452
- gem 'opal', '>= 1.3.0'
453
- ```
454
-
455
- <a id="markdown-motivation" name="motivation"></a>
456
- ## Motivation
457
-
458
- 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.
459
- 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.
460
-
461
- The original goal of Opal Zeitwerk was to bring a better autoloading mechanism for Isomorfeus.
462
-
463
- <a id="markdown-license" name="license"></a>
464
- ## License
465
-
466
- Released under the MIT License, Copyright (c) 2019–<i>ω</i> Xavier Noria, Jan Biedermann.
1
+ # Opal Zeitwerk
2
+
3
+ ## Community and Support
4
+ At the [Isomorfeus Project](https://isomorfeus.com) - isomorphic full stack Ruby for the web.
5
+
6
+ ## TOC
7
+ <!-- TOC -->
8
+
9
+ - [Introduction](#introduction)
10
+ - [Synopsis](#synopsis)
11
+ - [File structure](#file-structure)
12
+ - [The idea: File paths match constant paths](#the-idea-file-paths-match-constant-paths)
13
+ - [Inner simple constants](#inner-simple-constants)
14
+ - [Root directories and root namespaces](#root-directories-and-root-namespaces)
15
+ - [The default root namespace is `Object`](#the-default-root-namespace-is-object)
16
+ - [Custom root namespaces](#custom-root-namespaces)
17
+ - [Nested root directories](#nested-root-directories)
18
+ - [Implicit namespaces](#implicit-namespaces)
19
+ - [Explicit namespaces](#explicit-namespaces)
20
+ - [Collapsing directories](#collapsing-directories)
21
+ - [Testing compliance](#testing-compliance)
22
+ - [Usage](#usage)
23
+ - [Setup](#setup)
24
+ - [Generic](#generic)
25
+ - [for_gem](#for_gem)
26
+ - [Autoloading](#autoloading)
27
+ - [Eager loading](#eager-loading)
28
+ - [Eager load exclusions](#eager-load-exclusions)
29
+ - [Global eager load](#global-eager-load)
30
+ - [Reloading](#reloading)
31
+ - [Inflection](#inflection)
32
+ - [Zeitwerk::Inflector](#zeitwerkinflector)
33
+ - [Zeitwerk::GemInflector](#zeitwerkgeminflector)
34
+ - [Custom inflector](#custom-inflector)
35
+ - [Callbacks](#callbacks)
36
+ - [The on_setup callback](#the-on_setup-callback)
37
+ - [The on_load callback](#the-on_load-callback)
38
+ - [The on_unload callback](#the-on_unload-callback)
39
+ - [Technical details](#technical-details)
40
+ - [Logging](#logging)
41
+ - [Loader tag](#loader-tag)
42
+ - [Ignoring parts of the project](#ignoring-parts-of-the-project)
43
+ - [Use case: Files that do not follow the conventions](#use-case-files-that-do-not-follow-the-conventions)
44
+ - [Use case: The adapter pattern](#use-case-the-adapter-pattern)
45
+ - [Use case: Test files mixed with implementation files](#use-case-test-files-mixed-with-implementation-files)
46
+ - [Edge cases](#edge-cases)
47
+ - [Beware of circular dependencies](#beware-of-circular-dependencies)
48
+ - [Reopening third-party namespaces](#reopening-third-party-namespaces)
49
+ - [Rules of thumb](#rules-of-thumb)
50
+ - [Debuggers](#debuggers)
51
+ - [debug.rb](#debugrb)
52
+ - [Byebug](#byebug)
53
+ - [Break](#break)
54
+ - [Pronunciation](#pronunciation)
55
+ - [Supported Opal versions](#supported-opal-versions)
56
+ - [Testing](#testing)
57
+ - [Motivation](#motivation)
58
+ - [Kernel#require is brittle](#kernelrequire-is-brittle)
59
+ - [Rails autoloading was brittle](#rails-autoloading-was-brittle)
60
+ - [Thanks](#thanks)
61
+ - [License](#license)
62
+
63
+ <!-- /TOC -->
64
+
65
+ <a id="markdown-introduction" name="introduction"></a>
66
+ ## Introduction
67
+
68
+ Opal Zeitwerk is a port of the Ruby [Zeitwerk](https://github.com/fxn/zeitwerk) loader to Opal for autoloading ruby code in the Browser.
69
+ Autoloading reduces upfront TTI(time to interactive) for large opal projects vastly.
70
+
71
+ Zeitwerk is an efficient and thread-safe code loader for Ruby.
72
+
73
+ 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.
74
+
75
+ 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.
76
+
77
+ 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.
78
+
79
+ Internally, Opal Zeitwerk issues `require` calls exclusively using absolute path names as recorded in Opal modules registry.
80
+
81
+ Furthermore, Zeitwerk does at most one single scan of the project tree, and it descends into subdirectories lazily, only if their namespaces are used.
82
+
83
+ Differences to Ruby Zeitwerk:
84
+ - no logging (to keep asset size small and performance high)
85
+ - There are no threads in javascript so thread support has been removed.
86
+ - Tests don't run yet.
87
+ <a id="markdown-synopsis" name="synopsis"></a>
88
+ ## Synopsis
89
+
90
+ Main interface for gems:
91
+
92
+ ```ruby
93
+ # lib/my_gem.rb (main file)
94
+
95
+ require "zeitwerk"
96
+ loader = Zeitwerk::Loader.for_gem(__FILE__)
97
+ loader.setup # ready!
98
+
99
+ module MyGem
100
+ # ...
101
+ end
102
+
103
+ loader.eager_load # optionally
104
+ ```
105
+
106
+ Main generic interface:
107
+
108
+ ```ruby
109
+ loader = Zeitwerk::Loader.new
110
+ loader.push_dir(...)
111
+ loader.setup # ready!
112
+ ```
113
+
114
+ 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.
115
+
116
+ You can reload if you want to:
117
+
118
+ ```ruby
119
+ loader = Zeitwerk::Loader.new
120
+ loader.push_dir(...)
121
+ loader.enable_reloading # you need to opt-in before setup
122
+ loader.setup
123
+ ...
124
+ loader.reload
125
+ ```
126
+
127
+ and you can eager load all the code:
128
+
129
+ ```ruby
130
+ loader.eager_load
131
+ ```
132
+
133
+ It is also possible to broadcast `eager_load` to all instances:
134
+
135
+ ```ruby
136
+ Zeitwerk::Loader.eager_load_all
137
+ ```
138
+
139
+ <a id="markdown-file-structure" name="file-structure"></a>
140
+ ## File structure
141
+
142
+ <a id="markdown-the-idea-file-paths-match-constant-paths" name="the-idea-file-paths-match-constant-paths"></a>
143
+ ### The idea: File paths match constant paths
144
+
145
+ To have a file structure Zeitwerk can work with, just name files and directories after the name of the classes and modules they define:
146
+
147
+ ```
148
+ lib/my_gem.rb -> MyGem
149
+ lib/my_gem/foo.rb -> MyGem::Foo
150
+ lib/my_gem/bar_baz.rb -> MyGem::BarBaz
151
+ lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
152
+ ```
153
+
154
+ You can tune that a bit by [collapsing directories](#collapsing-directories), or by [ignoring parts of the project](#ignoring-parts-of-the-project), but that is the main idea.
155
+
156
+ <a id="markdown-inner-simple-constants" name="inner-simple-constants"></a>
157
+ ### Inner simple constants
158
+
159
+ While a simple constant like `HttpCrawler::MAX_RETRIES` can be defined in its own file:
160
+
161
+ ```ruby
162
+ # http_crawler/max_retries.rb
163
+ HttpCrawler::MAX_RETRIES = 10
164
+ ```
165
+
166
+ that is not required, you can also define it the regular way:
167
+
168
+ ```ruby
169
+ # http_crawler.rb
170
+ class HttpCrawler
171
+ MAX_RETRIES = 10
172
+ end
173
+ ```
174
+
175
+ The first example needs a custom [inflection](https://github.com/fxn/zeitwerk#inflection) rule:
176
+
177
+ ```ruby
178
+ loader.inflector.inflect("max_retries" => "MAX_RETRIES")
179
+ ```
180
+
181
+ Otherwise, Zeitwerk would expect the file to define `MaxRetries`.
182
+
183
+ In the second example, no custom rule is needed.
184
+
185
+ <a id="markdown-root-directories-and-root-namespaces" name="root-directories-and-root-namespaces"></a>
186
+ ### Root directories and root namespaces
187
+
188
+ Every directory configured with `push_dir` is called a _root directory_, and they represent _root namespaces_.
189
+
190
+ <a id="markdown-the-default-root-namespace-is-object" name="the-default-root-namespace-is-object"></a>
191
+ #### The default root namespace is `Object`
192
+
193
+ By default, the namespace associated to a root directory is the top-level one: `Object`.
194
+
195
+ For example, given
196
+
197
+ ```ruby
198
+ loader.push_dir("#{__dir__}/models")
199
+ loader.push_dir("#{__dir__}/serializers"))
200
+ ```
201
+
202
+ these are the expected classes and modules being defined by these files:
203
+
204
+ ```
205
+ models/user.rb -> User
206
+ serializers/user_serializer.rb -> UserSerializer
207
+ ```
208
+
209
+ <a id="markdown-custom-root-namespaces" name="custom-root-namespaces"></a>
210
+ #### Custom root namespaces
211
+
212
+ While `Object` is by far the most common root namespace, you can associate a different one to a particular root directory. The method `push_dir` accepts a class or module object in the optional `namespace` keyword argument.
213
+
214
+ For example, given:
215
+
216
+ ```ruby
217
+ require "active_job"
218
+ require "active_job/queue_adapters"
219
+ loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters)
220
+ ```
221
+
222
+ a file defining `ActiveJob::QueueAdapters::MyQueueAdapter` does not need the conventional parent directories, you can (and have to) store the file directly below `adapters`:
223
+
224
+ ```
225
+ adapters/my_queue_adapter.rb -> ActiveJob::QueueAdapters::MyQueueAdapter
226
+ ```
227
+
228
+ Please, note that the given root namespace must be non-reloadable, though autoloaded constants in that namespace can be. That is, if you associate `app/api` with an existing `Api` module, that module should not be reloadable. However, if the project defines and autoloads the class `Api::Deliveries`, that one can be reloaded.
229
+
230
+ <a id="markdown-nested-root-directories" name="nested-root-directories"></a>
231
+ #### Nested root directories
232
+
233
+ 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.
234
+
235
+ 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:
236
+
237
+ ```
238
+ app/models/concerns/geolocatable.rb
239
+ ```
240
+
241
+ should define `Geolocatable`, not `Concerns::Geolocatable`.
242
+
243
+ <a id="markdown-implicit-namespaces" name="implicit-namespaces"></a>
244
+ ### Implicit namespaces
245
+
246
+ Directories without a matching Ruby file get modules autovivified automatically by Zeitwerk. For example, in
247
+
248
+ ```
249
+ app/controllers/admin/users_controller.rb -> Admin::UsersController
250
+ ```
251
+
252
+ `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.
253
+
254
+ <a id="markdown-explicit-namespaces" name="explicit-namespaces"></a>
255
+ ### Explicit namespaces
256
+
257
+ Classes and modules that act as namespaces can also be explicitly defined, though. For instance, consider
258
+
259
+ ```
260
+ app/models/hotel.rb -> Hotel
261
+ app/models/hotel/pricing.rb -> Hotel::Pricing
262
+ ```
263
+
264
+ There, `app/models/hotel.rb` defines `Hotel`, and thus Zeitwerk does not autovivify a module.
265
+
266
+ The classes and modules from the namespace are already available in the body of the class or module defining it:
267
+
268
+ ```ruby
269
+ class Hotel < ApplicationRecord
270
+ include Pricing # works
271
+ ...
272
+ end
273
+ ```
274
+
275
+ 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.
276
+
277
+ <a id="markdown-collapsing-directories" name="collapsing-directories"></a>
278
+ ### Collapsing directories
279
+
280
+ 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:
281
+
282
+ ```
283
+ booking.rb -> Booking
284
+ booking/actions/create.rb -> Booking::Create
285
+ ```
286
+
287
+ To make it work that way, configure Zeitwerk to collapse said directory:
288
+
289
+ ```ruby
290
+ loader.collapse("#{__dir__}/booking/actions")
291
+ ```
292
+
293
+ This method accepts an arbitrary number of strings or `Pathname` objects, and also an array of them.
294
+
295
+ You can pass directories and glob patterns. Glob patterns are expanded when they are added, and again on each reload.
296
+
297
+ To illustrate usage of glob patterns, if `actions` in the example above is part of a standardized structure, you could use a wildcard:
298
+
299
+ ```ruby
300
+ loader.collapse("#{__dir__}/*/actions")
301
+ ```
302
+
303
+ <a id="markdown-testing-compliance" name="testing-compliance"></a>
304
+ ### Testing compliance
305
+
306
+ When a managed file is loaded, Zeitwerk verifies the expected constant is defined. If it is not, `Zeitwerk::NameError` is raised.
307
+
308
+ So, an easy way to ensure compliance in the test suite is to eager load the project:
309
+
310
+ ```ruby
311
+ begin
312
+ loader.eager_load(force: true)
313
+ rescue Zeitwerk::NameError => e
314
+ flunk e.message
315
+ else
316
+ assert true
317
+ end
318
+ ```
319
+
320
+ <a id="markdown-usage" name="usage"></a>
321
+ ## Usage
322
+
323
+ Add to the Gemfile:
324
+ ```
325
+ gem 'opal', '~> 1.4.1'
326
+ gem 'opal-zeitwerk', '~> 0.4.0'
327
+ ```
328
+
329
+ And to your loader of opal code:
330
+ ```
331
+ require 'zeitwerk'
332
+ ```
333
+
334
+ <a id="markdown-setup" name="setup"></a>
335
+ ### Setup
336
+
337
+ <a id="markdown-generic" name="generic"></a>
338
+ #### Generic
339
+ Files must be included in the compiled asset by:
340
+ ```
341
+ require_tree 'some_dir', autoload: true
342
+ ```
343
+ And added to the loader by:
344
+ ```
345
+ loader.push_dir('some_dir')
346
+ ```
347
+ The loader here requires the part of the path as it would appear in Opal.modules.
348
+ If `require_tree` is called from a sub directory, the path from the root as it would appear in Opal.modules has to be prepended for push_dir.
349
+
350
+ Loaders are ready to load code right after calling `setup` on them:
351
+
352
+ ```ruby
353
+ loader.setup
354
+ ```
355
+
356
+ This method is synchronized and idempotent.
357
+
358
+ Customization should generally be done before that call. In particular, in the generic interface you may set the root module paths from which you want to load files:
359
+
360
+ ```ruby
361
+ loader.push_dir(...)
362
+ loader.push_dir(...)
363
+ loader.setup
364
+ ```
365
+
366
+ Zeitwerk works internally only with absolute paths.
367
+
368
+ <a id="markdown-for_gem" name="for_gem"></a>
369
+ #### for_gem
370
+
371
+ `Zeitwerk::Loader.for_gem` is a convenience shortcut for the common case in which a gem has its entry point directly under the `lib` directory:
372
+
373
+ ```
374
+ lib/my_gem.rb # MyGem
375
+ lib/my_gem/version.rb # MyGem::VERSION
376
+ lib/my_gem/foo.rb # MyGem::Foo
377
+ ```
378
+
379
+ Neither a gemspec nor a version file are technically required, this helper works as long as the code is organized using that standard structure.
380
+
381
+ If the entry point of your gem lives in a subdirectory of `lib` because it is reopening a namespace defined somewhere else, please use the generic API to setup the loader, and make sure you check the section [_Reopening third-party namespaces_](https://github.com/fxn/zeitwerk#reopening-third-party-namespaces) down below.
382
+
383
+ Conceptually, `for_gem` translates to:
384
+
385
+ ```ruby
386
+ # lib/my_gem.rb
387
+
388
+ require "zeitwerk"
389
+ loader = Zeitwerk::Loader.new
390
+ loader.tag = File.basename(__FILE__, ".rb")
391
+ loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
392
+ loader.push_dir(__dir__)
393
+ ```
394
+
395
+ except that this method returns the same object in subsequent calls from the same file, in the unlikely case the gem wants to be able to reload.
396
+
397
+ If the main module references project constants at the top-level, Zeitwerk has to be ready to load them. Their definitions, in turn, may reference other project constants. And this is recursive. Therefore, it is important that the `setup` call happens above the main module definition:
398
+
399
+ ```ruby
400
+ # lib/my_gem.rb (main file)
401
+
402
+ require "zeitwerk"
403
+ loader = Zeitwerk::Loader.for_gem(__FILE__)
404
+ loader.setup
405
+
406
+ module MyGem
407
+ # Since the setup has been performed, at this point we are already able
408
+ # to reference project constants, in this case MyGem::MyLogger.
409
+ include MyLogger
410
+ end
411
+ ```
412
+
413
+ <a id="markdown-autoloading" name="autoloading"></a>
414
+ ### Autoloading
415
+
416
+ 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.
417
+
418
+ Let's revisit the example above:
419
+
420
+ ```ruby
421
+ # lib/my_gem.rb (main file)
422
+
423
+ require "zeitwerk"
424
+ loader = Zeitwerk::Loader.for_gem
425
+ loader.setup
426
+
427
+ module MyGem
428
+ include MyLogger # (*)
429
+ end
430
+ ```
431
+
432
+ That works, and there is no `require "my_gem/my_logger"`. When `(*)` is reached, Zeitwerk seamlessly autoloads `MyGem::MyLogger`.
433
+
434
+ If autoloading a file does not define the expected class or module, Zeitwerk raises `Zeitwerk::NameError`, which is a subclass of `NameError`.
435
+
436
+ <a id="markdown-eager-loading" name="eager-loading"></a>
437
+ ### Eager loading
438
+
439
+ Zeitwerk instances are able to eager load their managed files:
440
+
441
+ ```ruby
442
+ loader.eager_load
443
+ ```
444
+
445
+ That skips [ignored files and directories](#ignoring-parts-of-the-project).
446
+
447
+ 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).
448
+
449
+ Eager loading is synchronized and idempotent.
450
+
451
+ <a id="markdown-eager-load-exclusions" name="eager-load-exclusions"></a>
452
+ #### Eager load exclusions
453
+
454
+ You can tell Zeitwerk that certain files or directories are autoloadable, but should not be eager loaded:
455
+
456
+ ```ruby
457
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
458
+ loader.do_not_eager_load(db_adapters)
459
+ loader.setup
460
+ loader.eager_load # won't eager load the database adapters
461
+ ```
462
+
463
+ However, that can be overridden with `force`:
464
+
465
+ ```ruby
466
+ loader.eager_load(force: true) # database adapters are eager loaded
467
+ ```
468
+
469
+ Which may be handy if the project eager loads in the test suite to [ensure project layout compliance](#testing-compliance).
470
+
471
+ The `force` flag does not affect ignored files and directories, those are still ignored.
472
+
473
+ <a id="markdown-global-eager-load" name="global-eager-load"></a>
474
+ #### Global eager load
475
+
476
+ If you want to eager load yourself and all dependencies that use Zeitwerk, you can broadcast the `eager_load` call to all instances:
477
+
478
+ ```ruby
479
+ Zeitwerk::Loader.eager_load_all
480
+ ```
481
+
482
+ This may be handy in top-level services, like web applications.
483
+
484
+ Note that thanks to idempotence `Zeitwerk::Loader.eager_load_all` won't eager load twice if any of the instances already eager loaded.
485
+
486
+ This method does not accept the `force` flag, since in general it wouldn't be a good idea to force eager loading in 3rd party code.
487
+
488
+ <a id="markdown-reloading" name="reloading"></a>
489
+ ### Reloading
490
+
491
+ Zeitwerk is able to reload code, but you need to enable this feature:
492
+
493
+ ```ruby
494
+ loader = Zeitwerk::Loader.new
495
+ loader.push_dir(...)
496
+ loader.enable_reloading # you need to opt-in before setup
497
+ loader.setup
498
+ ...
499
+ loader.reload
500
+ ```
501
+
502
+ There is no way to undo this, either you want to reload or you don't.
503
+
504
+ Enabling reloading after setup raises `Zeitwerk::Error`. Attempting to reload without having it enabled raises `Zeitwerk::ReloadingDisabledError`.
505
+
506
+ 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.
507
+
508
+ Reloading removes the currently loaded classes and modules and resets the loader so that it will pick whatever is in the file system now.
509
+
510
+ It is important to highlight that this is an instance method. Don't worry about project dependencies managed by Zeitwerk, their loaders are independent.
511
+
512
+ 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.
513
+
514
+ 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.
515
+
516
+ <a id="markdown-inflection" name="inflection"></a>
517
+ ### Inflection
518
+
519
+ 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, and you can define your own.
520
+
521
+ <a id="markdown-zeitwerkinflector" name="zeitwerkinflector"></a>
522
+ #### Zeitwerk::Inflector
523
+
524
+ Each loader instantiated with `Zeitwerk::Loader.new` has an inflector of this type by default.
525
+
526
+ This is a very basic inflector that converts snake case to camel case:
527
+
528
+ ```
529
+ user -> User
530
+ users_controller -> UsersController
531
+ html_parser -> HtmlParser
532
+ ```
533
+
534
+ The camelize logic can be overridden easily for individual basenames:
535
+
536
+ ```ruby
537
+ loader.inflector.inflect(
538
+ "html_parser" => "HTMLParser",
539
+ "mysql_adapter" => "MySQLAdapter"
540
+ )
541
+ ```
542
+
543
+ The `inflect` method can be invoked several times if you prefer this other style:
544
+
545
+ ```ruby
546
+ loader.inflector.inflect "html_parser" => "HTMLParser"
547
+ loader.inflector.inflect "mysql_adapter" => "MySQLAdapter"
548
+ ```
549
+
550
+ Overrides need to be configured before calling `setup`.
551
+
552
+ The inflectors of different loaders are independent of each other. There are no global inflection rules or global configuration that can affect this inflector. It is deterministic.
553
+
554
+ <a id="markdown-zeitwerkgeminflector" name="zeitwerkgeminflector"></a>
555
+ #### Zeitwerk::GemInflector
556
+
557
+ Each loader instantiated with `Zeitwerk::Loader.for_gem` has an inflector of this type by default.
558
+
559
+ This inflector is like the basic one, except it expects `lib/my_gem/version.rb` to define `MyGem::VERSION`.
560
+
561
+ The inflectors of different loaders are independent of each other. There are no global inflection rules or global configuration that can affect this inflector. It is deterministic.
562
+
563
+ <a id="markdown-custom-inflector" name="custom-inflector"></a>
564
+ #### Custom inflector
565
+
566
+ The inflectors that ship with Zeitwerk are deterministic and simple. But you can configure your own:
567
+
568
+ ```ruby
569
+ # frozen_string_literal: true
570
+
571
+ class MyInflector < Zeitwerk::Inflector
572
+ def camelize(basename, abspath)
573
+ if basename =~ /\Ahtml_(.*)/
574
+ "HTML" + super($1, abspath)
575
+ else
576
+ super
577
+ end
578
+ end
579
+ end
580
+ ```
581
+
582
+ 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.
583
+
584
+ 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.
585
+
586
+ Then, assign the inflector:
587
+
588
+ ```ruby
589
+ loader.inflector = MyInflector.new
590
+ ```
591
+
592
+ This needs to be done before calling `setup`.
593
+
594
+ 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:
595
+
596
+ ```ruby
597
+ # lib/my_gem/inflector.rb
598
+ module MyGem
599
+ class Inflector < Zeitwerk::GemInflector
600
+ ...
601
+ end
602
+ end
603
+
604
+ # lib/my_gem.rb
605
+ require "zeitwerk"
606
+ require_relative "my_gem/inflector"
607
+
608
+ loader = Zeitwerk::Loader.for_gem
609
+ loader.inflector = MyGem::Inflector.new(__FILE__)
610
+ loader.setup
611
+
612
+ module MyGem
613
+ # ...
614
+ end
615
+ ```
616
+
617
+ Since `MyGem` is referenced before the namespace is defined in the main file, it is important to use this style:
618
+
619
+ ```ruby
620
+ # Correct, effectively defines MyGem.
621
+ module MyGem
622
+ class Inflector < Zeitwerk::GemInflector
623
+ # ...
624
+ end
625
+ end
626
+ ```
627
+
628
+ instead of:
629
+
630
+ ```ruby
631
+ # Raises uninitialized constant MyGem (NameError).
632
+ class MyGem::Inflector < Zeitwerk::GemInflector
633
+ # ...
634
+ end
635
+ ```
636
+
637
+ <a id="markdown-callbacks" name="callbacks"></a>
638
+ ### Callbacks
639
+
640
+ <a id="markdown-the-on_setup-callback" name="the-on_setup-callback"></a>
641
+ #### The on_setup callback
642
+
643
+ The `on_setup` callback is fired on setup and on each reload:
644
+
645
+ ```ruby
646
+ loader.on_setup do
647
+ # Ready to autoload here.
648
+ end
649
+ ```
650
+
651
+ Multiple `on_setup` callbacks are supported, and they run in order of definition.
652
+
653
+ If `setup` was already executed, the callback is fired immediately.
654
+
655
+ <a id="markdown-the-on_load-callback" name="the-on_load-callback"></a>
656
+ #### The on_load callback
657
+
658
+ The usual place to run something when a file is loaded is the file itself. However, sometimes you'd like to be called, and this is possible with the `on_load` callback.
659
+
660
+ For example, let's imagine this class belongs to a Rails application:
661
+
662
+ ```ruby
663
+ class SomeApiClient
664
+ class << self
665
+ attr_accessor :endpoint
666
+ end
667
+ end
668
+ ```
669
+
670
+ With `on_load`, it is easy to schedule code at boot time that initializes `endpoint` according to the configuration:
671
+
672
+ ```ruby
673
+ # config/environments/development.rb
674
+ loader.on_load("SomeApiClient") do |klass, _abspath|
675
+ klass.endpoint = "https://api.dev"
676
+ end
677
+
678
+ # config/environments/production.rb
679
+ loader.on_load("SomeApiClient") do |klass, _abspath|
680
+ klass.endpoint = "https://api.prod"
681
+ end
682
+ ```
683
+
684
+ Some uses cases:
685
+
686
+ * Doing something with a reloadable class or module in a Rails application during initialization, in a way that plays well with reloading. As in the previous example.
687
+ * Delaying the execution of the block until the class is loaded for performance.
688
+ * Delaying the execution of the block until the class is loaded because it follows the adapter pattern and better not to load the class if the user does not need it.
689
+
690
+ `on_load` gets a target constant path as a string (e.g., "User", or "Service::NotificationsGateway"). When fired, its block receives the stored value, and the absolute path to the corresponding file or directory as a string. The callback is executed every time the target is loaded. That includes reloads.
691
+
692
+ Multiple callbacks on the same target are supported, and they run in order of definition.
693
+
694
+ The block is executed once the loader has loaded the target. In particular, if the target was already loaded when the callback is defined, the block won't run. But if you reload and load the target again, then it will. Normally, you'll want to define `on_load` callbacks before `setup`.
695
+
696
+ Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
697
+
698
+ It is also possible to be called when any constant managed by the loader is loaded:
699
+
700
+ ```ruby
701
+ loader.on_load do |cpath, value, abspath|
702
+ # ...
703
+ end
704
+ ```
705
+
706
+ The block gets the constant path as a string (e.g., "User", or "Foo::VERSION"), the value it stores (e.g., the class object stored in `User`, or "2.5.0"), and the absolute path to the corresponding file or directory as a string.
707
+
708
+ Multiple callbacks like these are supported, and they run in order of definition.
709
+
710
+ There are use cases for this last catch-all callback, but they are rare. If you just need to understand how things are being loaded for debugging purposes, please remember that `Zeitwerk::Loader#log!` logs plenty of information.
711
+
712
+ If both types of callbacks are defined, the specific ones run first.
713
+
714
+ Since `on_load` callbacks are executed right after files are loaded, even if the loading context seems to be far away, in practice **the block is subject to [circular dependencies](#beware-of-circular-dependencies)**. As a rule of thumb, as far as loading order and its interdependencies is concerned, you have to program as if the block was executed at the bottom of the file just loaded.
715
+
716
+ <a id="markdown-the-on_unload-callback" name="the-on_unload-callback"></a>
717
+ #### The on_unload callback
718
+
719
+ When reloading is enabled, you may occasionally need to execute something before a certain autoloaded class or module is unloaded. The `on_unload` callback allows you to do that.
720
+
721
+ For example, let's imagine that a `Country` class fetches a list of countries and caches them when it is loaded. You might want to clear that cache if unloaded:
722
+
723
+ ```ruby
724
+ loader.on_unload("Country") do |klass, _abspath|
725
+ klass.clear_cache
726
+ end
727
+ ```
728
+
729
+ `on_unload` gets a target constant path as a string (e.g., "User", or "Service::NotificationsGateway"). When fired, its block receives the stored value, and the absolute path to the corresponding file or directory as a string. The callback is executed every time the target is unloaded.
730
+
731
+ `on_unload` blocks are executed before the class is unloaded, but in the middle of unloading, which happens in an unspecified order. Therefore, **that callback should not refer to any reloadable constant because there is no guarantee the constant works there**. Those blocks should rely on objects only, as in the example above, or regular constants not managed by the loader. This remark is transitive, applies to any methods invoked within the block.
732
+
733
+ Multiple callbacks on the same target are supported, and they run in order of definition.
734
+
735
+ Defining a callback for a target not managed by the receiver is not an error, the block simply won't ever be executed.
736
+
737
+ It is also possible to be called when any constant managed by the loader is unloaded:
738
+
739
+ ```ruby
740
+ loader.on_unload do |cpath, value, abspath|
741
+ # ...
742
+ end
743
+ ```
744
+
745
+ The block gets the constant path as a string (e.g., "User", or "Foo::VERSION"), the value it stores (e.g., the class object stored in `User`, or "2.5.0"), and the absolute path to the corresponding file or directory as a string.
746
+
747
+ Multiple callbacks like these are supported, and they run in order of definition.
748
+
749
+ If both types of callbacks are defined, the specific ones run first.
750
+
751
+ <a id="markdown-technical-details" name="technical-details"></a>
752
+ #### Technical details
753
+
754
+ Zeitwerk uses the word "unload" to ease communication and for symmetry with `on_load`. However, in Ruby you cannot unload things for real. So, when does `on_unload` technically happen?
755
+
756
+ When unloading, Zeitwerk issues `Module#remove_const` calls. Classes and modules are no longer reachable through their constants, and `on_unload` callbacks are executed right before those calls.
757
+
758
+ Technically, though, the objects themselves are still alive, but if everything is used as expected and they are not stored in any non-reloadable place (don't do that), they are ready for garbage collection, which is when the real unloading happens.
759
+
760
+ <a id="markdown-logging" name="logging"></a>
761
+ ### Logging
762
+
763
+ 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.
764
+
765
+ The `log!` method is a quick shortcut to let the loader log to `$stdout`:
766
+
767
+ ```
768
+ loader.log!
769
+ ```
770
+
771
+ If you want more control, a logger can be configured as a callable
772
+
773
+ ```ruby
774
+ loader.logger = method(:puts)
775
+ loader.logger = ->(msg) { ... }
776
+ ```
777
+
778
+ as well as anything that responds to `debug`:
779
+
780
+ ```ruby
781
+ loader.logger = Logger.new($stderr)
782
+ loader.logger = Rails.logger
783
+ ```
784
+
785
+ In both cases, the corresponding methods are going to be passed exactly one argument with the message to be logged.
786
+
787
+ It is also possible to set a global default this way:
788
+
789
+ ```ruby
790
+ Zeitwerk::Loader.default_logger = method(:puts)
791
+ ```
792
+
793
+ 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.
794
+
795
+ 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.
796
+
797
+ <a id="markdown-loader-tag" name="loader-tag"></a>
798
+ #### Loader tag
799
+
800
+ Loaders have a tag that is printed in traces in order to be able to distinguish them in globally logged activity:
801
+
802
+ ```
803
+ Zeitwerk@9fa54b: autoload set for User, to be loaded from ...
804
+ ```
805
+
806
+ By default, a random tag like the one above is assigned, but you can change it:
807
+
808
+ ```
809
+ loader.tag = "grep_me"
810
+ ```
811
+
812
+ The tag of a loader returned by `for_gem` is the basename of the root file without extension:
813
+
814
+ ```
815
+ Zeitwerk@my_gem: constant MyGem::Foo loaded from ...
816
+ ```
817
+
818
+ <a id="markdown-ignoring-parts-of-the-project" name="ignoring-parts-of-the-project"></a>
819
+ ### Ignoring parts of the project
820
+
821
+ Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have extension ".rb".
822
+
823
+ 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.
824
+
825
+ You can ignore file names, directory names, and glob patterns. Glob patterns are expanded when they are added and again on each reload.
826
+
827
+ Let's see some use cases.
828
+
829
+ <a id="markdown-use-case-files-that-do-not-follow-the-conventions" name="use-case-files-that-do-not-follow-the-conventions"></a>
830
+ #### Use case: Files that do not follow the conventions
831
+
832
+ Let's suppose that your gem decorates something in `Kernel`:
833
+
834
+ ```ruby
835
+ # lib/my_gem/core_ext/kernel.rb
836
+
837
+ Kernel.module_eval do
838
+ # ...
839
+ end
840
+ ```
841
+
842
+ `Kernel` is already defined by Ruby so the module cannot be autoloaded. Also, that file does not define a constant path after the path name. Therefore, Zeitwerk should not process it at all.
843
+
844
+ The extension can still coexist with the rest of the project, you only need to tell Zeitwerk to ignore it:
845
+
846
+ ```ruby
847
+ kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb"
848
+ loader.ignore(kernel_ext)
849
+ loader.setup
850
+ ```
851
+
852
+ You can also ignore the whole directory:
853
+
854
+ ```ruby
855
+ core_ext = "#{__dir__}/my_gem/core_ext"
856
+ loader.ignore(core_ext)
857
+ loader.setup
858
+ ```
859
+
860
+ Now, that file has to be loaded manually with `require` or `require_relative`:
861
+
862
+ ```ruby
863
+ require_relative "my_gem/core_ext/kernel"
864
+ ```
865
+
866
+ and you can do that anytime, before configuring the loader, or after configuring the loader, does not matter.
867
+
868
+ <a id="markdown-use-case-the-adapter-pattern" name="use-case-the-adapter-pattern"></a>
869
+ #### Use case: The adapter pattern
870
+
871
+ Another use case for ignoring files is the adapter pattern.
872
+
873
+ 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:
874
+
875
+ ```ruby
876
+ # my_gem/db_adapters/postgresql.rb
877
+ require "pg"
878
+ ```
879
+
880
+ but you don't want your users to install them all, only the one they are going to use.
881
+
882
+ 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:
883
+
884
+ ```ruby
885
+ db_adapters = "#{__dir__}/my_gem/db_adapters"
886
+ loader.ignore(db_adapters)
887
+ loader.setup
888
+ ```
889
+
890
+ The chosen adapter, then, has to be loaded by hand somehow:
891
+
892
+ ```ruby
893
+ require "my_gem/db_adapters/#{config[:db_adapter]}"
894
+ ```
895
+
896
+ 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.
897
+
898
+ <a id="markdown-use-case-test-files-mixed-with-implementation-files" name="use-case-test-files-mixed-with-implementation-files"></a>
899
+ #### Use case: Test files mixed with implementation files
900
+
901
+ 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:
902
+
903
+ ```ruby
904
+ tests = "#{__dir__}/**/*_test.rb"
905
+ loader.ignore(tests)
906
+ loader.setup
907
+ ```
908
+
909
+ <a id="markdown-edge-cases" name="edge-cases"></a>
910
+ ### Edge cases
911
+
912
+ A class or module that acts as a namespace:
913
+
914
+ ```ruby
915
+ # trip.rb
916
+ class Trip
917
+ include Geolocation
918
+ end
919
+
920
+ # trip/geolocation.rb
921
+ module Trip::Geolocation
922
+ ...
923
+ end
924
+ ```
925
+
926
+ has to be defined with the `class` or `module` keywords, as in the example above.
927
+
928
+ For technical reasons, raw constant assignment is not supported:
929
+
930
+ ```ruby
931
+ # trip.rb
932
+ Trip = Class.new { ... } # NOT SUPPORTED
933
+ Trip = Struct.new { ... } # NOT SUPPORTED
934
+ ```
935
+
936
+ This only affects explicit namespaces, those idioms work well for any other ordinary class or module.
937
+
938
+ <a id="markdown-beware-of-circular-dependencies" name="beware-of-circular-dependencies"></a>
939
+ ### Beware of circular dependencies
940
+
941
+ In Ruby, you can't have certain top-level circular dependencies. Take for example:
942
+
943
+ ```ruby
944
+ # c.rb
945
+ class C < D
946
+ end
947
+
948
+ # d.rb
949
+ class D
950
+ C
951
+ end
952
+ ```
953
+
954
+ In order to define `C`, you need to load `D`. However, the body of `D` refers to `C`.
955
+
956
+ Circular dependencies like those do not work in plain Ruby, and therefore do not work in projects managed by Zeitwerk either.
957
+
958
+ <a id="markdown-reopening-third-party-namespaces" name="reopening-third-party-namespaces"></a>
959
+ ### Reopening third-party namespaces
960
+
961
+ Projects managed by Zeitwerk can work with namespaces defined by third-party libraries. However, they have to be loaded in memory before calling `setup`.
962
+
963
+ For example, let's imagine you're writing a gem that implements an adapter for [Active Job](https://guides.rubyonrails.org/active_job_basics.html) that uses AwesomeQueue as backend. By convention, your gem has to define a class called `ActiveJob::QueueAdapters::AwesomeQueue`, and it has to do so in a file with a matching path:
964
+
965
+ ```ruby
966
+ # lib/active_job/queue_adapters/awesome_queue.rb
967
+ module ActiveJob
968
+ module QueueAdapters
969
+ class AwesomeQueue
970
+ # ...
971
+ end
972
+ end
973
+ end
974
+ ```
975
+
976
+ It is very important that your gem _reopens_ the modules `ActiveJob` and `ActiveJob::QueueAdapters` instead of _defining_ them. Because their proper definition lives in Active Job. Furthermore, if the project reloads, you do not want any of `ActiveJob` or `ActiveJob::QueueAdapters` to be reloaded.
977
+
978
+ Bottom line, Zeitwerk should not be managing those namespaces. Active Job owns them and defines them. Your gem needs to _reopen_ them.
979
+
980
+ In order to do so, you need to make sure those modules are loaded before calling `setup`. For instance, in the entry file for the gem:
981
+
982
+ ```ruby
983
+ # Ensure these namespaces are reopened, not defined.
984
+ require "active_job"
985
+ require "active_job/queue_adapters"
986
+
987
+ require "zeitwerk"
988
+ loader = Zeitwerk::Loader.for_gem
989
+ loader.setup
990
+ ```
991
+
992
+ With that, when Zeitwerk scans the file system and reaches the gem directories `lib/active_job` and `lib/active_job/queue_adapters`, it detects the corresponding modules already exist and therefore understands it does not have to manage them. The loader just descends into those directories. Eventually will reach `lib/active_job/queue_adapters/awesome_queue.rb`, and since `ActiveJob::QueueAdapters::AwesomeQueue` is unknown, Zeitwerk will manage it. Which is what happens regularly with the files in your gem. On reload, the namespaces are safe, won't be reloaded. The loader only reloads what it manages, which in this case is the adapter itself.
993
+
994
+ <a id="markdown-rules-of-thumb" name="rules-of-thumb"></a>
995
+ ### Rules of thumb
996
+
997
+ 1. Different loaders should manage different directory trees. It is an error condition to configure overlapping root directories in different loaders.
998
+
999
+ 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).
1000
+
1001
+ 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.
1002
+
1003
+ 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.
1004
+
1005
+ 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.
1006
+
1007
+ 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.
1008
+
1009
+ <a id="markdown-debuggers" name="debuggers"></a>
1010
+ ### Debuggers
1011
+
1012
+ <a id="markdown-debugrb" name="debugrb"></a>
1013
+ #### debug.rb
1014
+
1015
+ The new [debug.rb](https://github.com/ruby/debug) gem and Zeitwerk are mostly compatible. This is the new debugger that is going to ship with Ruby 3.1.
1016
+
1017
+ There's one exception, though: Due to a technical limitation of tracepoints, explicit namespaces are not autoloaded while expressions are evaluated in the REPL. See [ruby/debug#408](https://github.com/ruby/debug/issues/408).
1018
+
1019
+ <a id="markdown-byebug" name="byebug"></a>
1020
+ #### Byebug
1021
+
1022
+ Zeitwerk and [Byebug](https://github.com/deivid-rodriguez/byebug) have a similar edge incompatibility.
1023
+
1024
+ <a id="markdown-break" name="break"></a>
1025
+ #### Break
1026
+
1027
+ Zeitwerk works fine with [@gsamokovarov](https://github.com/gsamokovarov)'s [Break](https://github.com/gsamokovarov/break) debugger.
1028
+
1029
+ <a id="markdown-pronunciation" name="pronunciation"></a>
1030
+ ## Pronunciation
1031
+
1032
+ "Zeitwerk" is pronounced [this way](http://share.hashref.com/zeitwerk/zeitwerk_pronunciation.mp3).
1033
+
1034
+ <a id="markdown-supported-opal-versions" name="supported-opal-versions"></a>
1035
+ ## Supported Opal versions
1036
+
1037
+ Opal Zeitwerk currently works with Opal releases >= 1.3.0. For the Gemfile:
1038
+ ```
1039
+ gem 'opal', '>= 1.4.0'
1040
+ ```
1041
+
1042
+ <a id="markdown-motivation" name="motivation"></a>
1043
+ ## Motivation
1044
+
1045
+ <a id="markdown-kernelrequire-is-brittle" name="kernelrequire-is-brittle"></a>
1046
+ ### Kernel#require is brittle
1047
+
1048
+ 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.
1049
+
1050
+ Also, if the project has namespaces, setting things up and getting client code to load things in a consistent way needs discipline. For example, `require "foo/bar"` may define `Foo`, instead of reopen it. That may be a broken window, giving place to superclass mismatches or partially-defined namespaces.
1051
+
1052
+ With Zeitwerk, you just name things following conventions and done. Things are available everywhere, and descend is always orderly. Without effort and without broken windows.
1053
+
1054
+ <a id="markdown-rails-autoloading-was-brittle" name="rails-autoloading-was-brittle"></a>
1055
+ ### Rails autoloading was brittle
1056
+
1057
+ Autoloading in Rails was based on `const_missing` up to Rails 5. That callback lacks fundamental information like the nesting or the resolution algorithm being used. Because of that, Rails autoloading was not able to match Ruby's semantics, and that introduced a [series of issues](https://guides.rubyonrails.org/v5.2/autoloading_and_reloading_constants.html#common-gotchas). Zeitwerk is based on a different technique and fixed Rails autoloading starting with Rails 6.
1058
+
1059
+ <a id="markdown-thanks" name="thanks"></a>
1060
+ ## Thanks
1061
+
1062
+ 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.
1063
+
1064
+ 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.
1065
+
1066
+ 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 ❤️.
1067
+
1068
+ 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. 💯
1069
+
1070
+ <a id="markdown-license" name="license"></a>
1071
+ ## License
1072
+
1073
+ Released under the MIT License, Copyright (c) 2019–<i>ω</i> Xavier Noria, Jan Biedermann.