Class: Zeitwerk::Loader

Inherits:
Object
  • Object
show all
Includes:
Callbacks, Config, Helpers, RealModName
Defined in:
lib/zeitwerk/loader.rb

Defined Under Namespace

Modules: Callbacks, Config, Helpers

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes included from Config

#collapse_dirs, #collapse_glob_patterns, #eager_load_exclusions, #ignored_glob_patterns, #ignored_paths, #inflector, #logger, #on_load_callbacks, #on_setup_callbacks, #on_unload_callbacks, #root_dirs

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Config

#collapse, #dirs, #do_not_eager_load, #enable_reloading, #ignore, #ignores?, #log!, #on_load, #on_setup, #on_unload, #push_dir, #reloading_enabled?, #tag, #tag=

Methods included from Callbacks

#on_dir_autoloaded, #on_file_autoloaded, #on_namespace_loaded

Methods included from RealModName

#real_mod_name

Constructor Details

#initializeLoader

Returns a new instance of Loader.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/zeitwerk/loader.rb', line 81

def initialize
  super

  @autoloads       = {}
  @autoloaded_dirs = []
  @to_unload       = {}
  @lazy_subdirs    = Hash.new { |h, cpath| h[cpath] = [] }
  @mutex           = Mutex.new
  @mutex2          = Mutex.new
  @setup           = false
  @eager_loaded    = false

  Registry.register_loader(self)
end

Class Attribute Details

.default_loggerObject

Returns the value of attribute default_logger.



285
286
287
# File 'lib/zeitwerk/loader.rb', line 285

def default_logger
  @default_logger
end

.mutexObject



289
290
291
# File 'lib/zeitwerk/loader.rb', line 289

def mutex
  @mutex
end

Instance Attribute Details

#autoloaded_dirsObject (readonly)

We keep track of autoloaded directories to remove them from the registry at the end of eager loading.

Files are removed as they are autoloaded, but directories need to wait due to concurrency (see why in Zeitwerk::Loader::Callbacks#on_dir_autoloaded).



37
38
39
# File 'lib/zeitwerk/loader.rb', line 37

def autoloaded_dirs
  @autoloaded_dirs
end

#autoloadsObject (readonly)

Maps absolute paths for which an autoload has been set —and not executed— to their corresponding parent class or module and constant name.

"/Users/fxn/blog/app/models/user.rb"          => [Object, :User],
"/Users/fxn/blog/app/models/hotel/pricing.rb" => [Hotel, :Pricing]
...


27
28
29
# File 'lib/zeitwerk/loader.rb', line 27

def autoloads
  @autoloads
end

#lazy_subdirsObject (readonly)

Maps constant paths of namespaces to arrays of corresponding directories.

For example, given this mapping:

"Admin" => [
  "/Users/fxn/blog/app/controllers/admin",
  "/Users/fxn/blog/app/models/admin",
  ...
]

when ‘Admin` gets defined we know that it plays the role of a namespace and that its children are spread over those directories. We’ll visit them to set up the corresponding autoloads.



71
72
73
# File 'lib/zeitwerk/loader.rb', line 71

def lazy_subdirs
  @lazy_subdirs
end

#mutexObject (readonly)



75
76
77
# File 'lib/zeitwerk/loader.rb', line 75

def mutex
  @mutex
end

#mutex2Object (readonly)



79
80
81
# File 'lib/zeitwerk/loader.rb', line 79

def mutex2
  @mutex2
end

#to_unloadObject (readonly)

Stores metadata needed for unloading. Its entries look like this:

"Admin::Role" => [".../admin/role.rb", [Admin, :Role]]

The cpath as key helps implementing unloadable_cpath? The file name is stored in order to be able to delete it from $LOADED_FEATURES, and the pair [Module, Symbol] is used to remove_const the constant from the class or module object.

If reloading is enabled, this hash is filled as constants are autoloaded or eager loaded. Otherwise, the collection remains empty.



53
54
55
# File 'lib/zeitwerk/loader.rb', line 53

def to_unload
  @to_unload
end

Class Method Details

.all_dirsObject

Returns an array with the absolute paths of the root directories of all registered loaders. This is a read-only collection.



319
320
321
# File 'lib/zeitwerk/loader.rb', line 319

def all_dirs
  Registry.loaders.flat_map(&:dirs).freeze
end

.eager_load_allObject

Broadcasts ‘eager_load` to all loaders.



311
312
313
# File 'lib/zeitwerk/loader.rb', line 311

def eager_load_all
  Registry.loaders.each(&:eager_load)
end

.for_gemObject

This is a shortcut for

require "zeitwerk"
loader = Zeitwerk::Loader.new
loader.tag = File.basename(__FILE__, ".rb")
loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
loader.push_dir(__dir__)

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.



303
304
305
306
# File 'lib/zeitwerk/loader.rb', line 303

def for_gem
  called_from = caller_locations(1, 1).first.path
  Registry.loader_for_gem(called_from)
end

Instance Method Details

#eager_load(force: false) ⇒ Object

Eager loads all files in the root directories, recursively. Files do not need to be in ‘$LOAD_PATH`, absolute file names are used. Ignored files are not eager loaded. You can opt-out specifically in specific files and directories with `do_not_eager_load`, and that can be overridden passing `force: true`.



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/zeitwerk/loader.rb', line 211

def eager_load(force: false)
  mutex.synchronize do
    break if @eager_loaded

    log("eager load start") if logger

    honour_exclusions = !force

    queue = []
    actual_root_dirs.each do |root_dir, namespace|
      queue << [namespace, root_dir] unless honour_exclusions && excluded_from_eager_load?(root_dir)
    end

    while to_eager_load = queue.shift
      namespace, dir = to_eager_load

      ls(dir) do |basename, abspath|
        next if honour_exclusions && excluded_from_eager_load?(abspath)

        if ruby?(abspath)
          if cref = autoloads[abspath]
            cget(*cref)
          end
        elsif dir?(abspath) && !root_dirs.key?(abspath)
          if collapse?(abspath)
            queue << [namespace, abspath]
          else
            cname = inflector.camelize(basename, abspath)
            queue << [cget(namespace, cname), abspath]
          end
        end
      end
    end

    autoloaded_dirs.each do |autoloaded_dir|
      Registry.unregister_autoload(autoloaded_dir)
    end
    autoloaded_dirs.clear

    @eager_loaded = true

    log("eager load end") if logger
  end
end

#reloadObject

Unloads all loaded code, and calls setup again so that the loader is able to pick any changes in the file system.

This method is not thread-safe, please see how this can be achieved by client code in the README of the project.

Raises:



193
194
195
196
197
198
199
200
201
202
# File 'lib/zeitwerk/loader.rb', line 193

def reload
  if reloading_enabled?
    unload
    recompute_ignored_paths
    recompute_collapse_dirs
    setup
  else
    raise ReloadingDisabledError, "can't reload, please call loader.enable_reloading before setup"
  end
end

#setupObject

Sets autoloads in the root namespace.



99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/zeitwerk/loader.rb', line 99

def setup
  mutex.synchronize do
    break if @setup

    actual_root_dirs.each do |root_dir, namespace|
      set_autoloads_in_dir(root_dir, namespace)
    end

    on_setup_callbacks.each(&:call)

    @setup = true
  end
end

#unloadObject

Removes loaded constants and configured autoloads.

The objects the constants stored are no longer reachable through them. In addition, since said objects are normally not referenced from anywhere else, they are eligible for garbage collection, which would effectively unload them.

This method is public but undocumented. Main interface is ‘reload`, which means `unload` + `setup`. This one is avaiable to be used together with `unregister`, which is undocumented too.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/zeitwerk/loader.rb', line 125

def unload
  mutex.synchronize do
    # We are going to keep track of the files that were required by our
    # autoloads to later remove them from $LOADED_FEATURES, thus making them
    # loadable by Kernel#require again.
    #
    # Directories are not stored in $LOADED_FEATURES, keeping track of files
    # is enough.
    unloaded_files = Set.new

    autoloads.each do |abspath, (parent, cname)|
      if parent.autoload?(cname)
        unload_autoload(parent, cname)
      else
        # Could happen if loaded with require_relative. That is unsupported,
        # and the constant path would escape unloadable_cpath? This is just
        # defensive code to clean things up as much as we are able to.
        unload_cref(parent, cname)
        unloaded_files.add(abspath) if ruby?(abspath)
      end
    end

    to_unload.each do |cpath, (abspath, (parent, cname))|
      unless on_unload_callbacks.empty?
        value = parent.const_get(cname)
        run_on_unload_callbacks(cpath, value, abspath)
      end

      unload_cref(parent, cname)
      unloaded_files.add(abspath) if ruby?(abspath)
    end

    unless unloaded_files.empty?
      # Bootsnap decorates Kernel#require to speed it up using a cache and
      # this optimization does not check if $LOADED_FEATURES has the file.
      #
      # To make it aware of changes, the gem defines singleton methods in
      # $LOADED_FEATURES:
      #
      #   https://github.com/Shopify/bootsnap/blob/master/lib/bootsnap/load_path_cache/core_ext/loaded_features.rb
      #
      # Rails applications may depend on bootsnap, so for unloading to work
      # in that setting it is preferable that we restrict our API choice to
      # one of those methods.
      $LOADED_FEATURES.reject! { |file| unloaded_files.member?(file) }
    end

    autoloads.clear
    autoloaded_dirs.clear
    to_unload.clear
    lazy_subdirs.clear

    Registry.on_unload(self)
    ExplicitNamespace.unregister_loader(self)

    @setup        = false
    @eager_loaded = false
  end
end

#unloadable_cpath?(cpath) ⇒ Boolean

Says if the given constant path would be unloaded on reload. This predicate returns ‘false` if reloading is disabled.

Returns:

  • (Boolean)


260
261
262
# File 'lib/zeitwerk/loader.rb', line 260

def unloadable_cpath?(cpath)
  to_unload.key?(cpath)
end

#unloadable_cpathsObject

Returns an array with the constant paths that would be unloaded on reload. This predicate returns an empty array if reloading is disabled.



268
269
270
# File 'lib/zeitwerk/loader.rb', line 268

def unloadable_cpaths
  to_unload.keys.freeze
end

#unregisterObject

This is a dangerous method.



276
277
278
279
# File 'lib/zeitwerk/loader.rb', line 276

def unregister
  Registry.unregister_loader(self)
  ExplicitNamespace.unregister_loader(self)
end