Class: Zeitwerk::Loader
- Inherits:
-
Object
- Object
- Zeitwerk::Loader
- Includes:
- Callbacks
- Defined in:
- lib/zeitwerk/loader.rb
Defined Under Namespace
Modules: Callbacks
Class Attribute Summary collapse
Instance Attribute Summary collapse
-
#autoloads ⇒ {String => (Module, String)}
readonly
Maps real absolute paths for which an autoload has been set to their corresponding parent class or module and constant name.
-
#eager_load_exclusions ⇒ Set<String>
readonly
Absolute paths of files or directories not to be eager loaded.
-
#ignored ⇒ Set<String>
readonly
Absolute paths of files, directories, of glob patterns to be totally ignored.
-
#ignored_paths ⇒ Set<String>
readonly
The actual collection of absolute file and directory names at the time the ignored glob patterns were expanded.
- #inflector ⇒ #camelize
-
#lazy_subdirs ⇒ {String => <String>}
readonly
Maps constant paths of namespaces to arrays of corresponding directories.
-
#loaded_cpaths ⇒ Set<String>
readonly
Constant paths loaded so far.
- #logger ⇒ #call, ...
- #mutex ⇒ Mutex readonly
- #mutex2 ⇒ Mutex readonly
-
#preloads ⇒ <String>
readonly
Absolute paths of files or directories that have to be preloaded.
-
#root_dirs ⇒ {String => true}
readonly
Absolute paths of the root directories.
-
#shadowed_files ⇒ {String => String}
readonly
Keeps track of shadowed files.
- #tag ⇒ String
Class Method Summary collapse
-
.all_dirs ⇒ <String>
Returns an array with the absolute paths of the root directories of all registered loaders.
-
.eager_load_all ⇒ void
Broadcasts ‘eager_load` to all loaders.
-
.for_gem ⇒ Zeitwerk::Loader
This is a shortcut for.
Instance Method Summary collapse
-
#dirs ⇒ <String>
Absolute paths of the root directories.
-
#do_not_eager_load(*paths) ⇒ void
Let eager load ignore the given files or directories.
-
#eager_load ⇒ void
Eager loads all files in the root directories, recursively.
- #expand_ignored_glob_patterns ⇒ void
-
#ignore(*paths) ⇒ void
Configure files, directories, or glob patterns to be totally ignored.
-
#initialize ⇒ Loader
constructor
A new instance of Loader.
-
#loaded?(cpath) ⇒ Boolean
Says if the given constant path has been loaded.
-
#preload(*paths) ⇒ void
Files or directories to be preloaded instead of lazy loaded.
-
#push_dir(path) ⇒ void
Pushes ‘paths` to the list of root directories.
-
#reload ⇒ void
Unloads all loaded code, and calls setup again so that the loader is able to pick any changes in the file system.
-
#setup ⇒ void
Sets autoloads in the root namespace and preloads files, if any.
-
#unload ⇒ void
Removes loaded constants and configured autoloads.
Methods included from Callbacks
#on_dir_autoloaded, #on_file_autoloaded, #on_namespace_loaded
Constructor Details
#initialize ⇒ Loader
Returns a new instance of Loader.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/zeitwerk/loader.rb', line 120 def initialize @initialized_at = Time.now @tag = SecureRandom.hex(3) @inflector = Inflector.new @logger = self.class.default_logger @root_dirs = {} @preloads = [] @ignored = Set.new @ignored_paths = Set.new @autoloads = {} @loaded_cpaths = Set.new @lazy_subdirs = {} @shadowed_files = {} @eager_load_exclusions = Set.new # TODO: find a better name for these mutexes. @mutex = Mutex.new @mutex2 = Mutex.new @setup = false @eager_loaded = false Registry.register_loader(self) end |
Class Attribute Details
.default_logger ⇒ #call, ...
329 330 331 |
# File 'lib/zeitwerk/loader.rb', line 329 def default_logger @default_logger end |
.mutex ⇒ Mutex
333 334 335 |
# File 'lib/zeitwerk/loader.rb', line 333 def mutex @mutex end |
Instance Attribute Details
#autoloads ⇒ {String => (Module, String)} (readonly)
Maps real absolute paths for which an autoload has been set 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"]
...
80 81 82 |
# File 'lib/zeitwerk/loader.rb', line 80 def autoloads @autoloads end |
#eager_load_exclusions ⇒ Set<String> (readonly)
Absolute paths of files or directories not to be eager loaded.
110 111 112 |
# File 'lib/zeitwerk/loader.rb', line 110 def eager_load_exclusions @eager_load_exclusions end |
#ignored ⇒ Set<String> (readonly)
Absolute paths of files, directories, of glob patterns to be totally ignored.
46 47 48 |
# File 'lib/zeitwerk/loader.rb', line 46 def ignored @ignored end |
#ignored_paths ⇒ Set<String> (readonly)
The actual collection of absolute file and directory names at the time the ignored glob patterns were expanded. Computed on setup, and recomputed on reload.
54 55 56 |
# File 'lib/zeitwerk/loader.rb', line 54 def ignored_paths @ignored_paths end |
#inflector ⇒ #camelize
15 16 17 |
# File 'lib/zeitwerk/loader.rb', line 15 def inflector @inflector end |
#lazy_subdirs ⇒ {String => <String>} (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.
104 105 106 |
# File 'lib/zeitwerk/loader.rb', line 104 def lazy_subdirs @lazy_subdirs end |
#loaded_cpaths ⇒ Set<String> (readonly)
Constant paths loaded so far.
86 87 88 |
# File 'lib/zeitwerk/loader.rb', line 86 def loaded_cpaths @loaded_cpaths end |
#logger ⇒ #call, ...
18 19 20 |
# File 'lib/zeitwerk/loader.rb', line 18 def logger @logger end |
#mutex ⇒ Mutex (readonly)
114 115 116 |
# File 'lib/zeitwerk/loader.rb', line 114 def mutex @mutex end |
#mutex2 ⇒ Mutex (readonly)
118 119 120 |
# File 'lib/zeitwerk/loader.rb', line 118 def mutex2 @mutex2 end |
#preloads ⇒ <String> (readonly)
Absolute paths of files or directories that have to be preloaded.
39 40 41 |
# File 'lib/zeitwerk/loader.rb', line 39 def preloads @preloads end |
#root_dirs ⇒ {String => true} (readonly)
Absolute paths of the root directories. Stored in a hash to preserve order, easily handle duplicates, and also be able to have a fast lookup, needed for detecting nested paths.
"/Users/fxn/blog/app/assets" => true,
"/Users/fxn/blog/app/channels" => true,
...
This is a private collection maintained by the loader. The public interface for it is ‘push_dir` and `dirs`.
33 34 35 |
# File 'lib/zeitwerk/loader.rb', line 33 def root_dirs @root_dirs end |
#shadowed_files ⇒ {String => String} (readonly)
Keeps track of shadowed files.
A shadowed file is a file managed by this autoloader that is skipped because its matching constant path has already been seen. Think $LOAD_PATH and require, only the first occurrence of a given relative name is loaded.
If the existing occurrence is an autoload, we map the file name to the shadowing autoload path. If the existing occurrence is an already defined constant, the file name is mapped to the constant path, meaning it was loaded elsewhere.
69 70 71 |
# File 'lib/zeitwerk/loader.rb', line 69 def shadowed_files @shadowed_files end |
#tag ⇒ String
12 13 14 |
# File 'lib/zeitwerk/loader.rb', line 12 def tag @tag end |
Class Method Details
.all_dirs ⇒ <String>
Returns an array with the absolute paths of the root directories of all registered loaders. This is a read-only collection.
363 364 365 |
# File 'lib/zeitwerk/loader.rb', line 363 def all_dirs Registry.loaders.flat_map(&:dirs).freeze end |
.eager_load_all ⇒ void
This method returns an undefined value.
Broadcasts ‘eager_load` to all loaders.
355 356 357 |
# File 'lib/zeitwerk/loader.rb', line 355 def eager_load_all Registry.loaders.each(&:eager_load) end |
.for_gem ⇒ Zeitwerk::Loader
This is a shortcut for
require "zeitwerk"
loader = Zeitwerk::Loader.new
loader.tag = File.basename(__FILE__, ".rb")
loader.inflector = Zeitwerk::GemInflector.new
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.
347 348 349 350 |
# File 'lib/zeitwerk/loader.rb', line 347 def for_gem called_from = caller[0].split(':')[0] Registry.loader_for_gem(called_from) end |
Instance Method Details
#dirs ⇒ <String>
Absolute paths of the root directories. This is a read-only collection, please push here via ‘push_dir`.
157 158 159 |
# File 'lib/zeitwerk/loader.rb', line 157 def dirs root_dirs.keys.freeze end |
#do_not_eager_load(*paths) ⇒ void
This method returns an undefined value.
Let eager load ignore the given files or directories. The constants defined in those files are still autoloadable.
313 314 315 |
# File 'lib/zeitwerk/loader.rb', line 313 def do_not_eager_load(*paths) mutex.synchronize { eager_load_exclusions.merge((paths)) } end |
#eager_load ⇒ void
This method returns an undefined value.
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`.
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/zeitwerk/loader.rb', line 287 def eager_load mutex.synchronize do break if @eager_loaded queue = non_ignored_root_dirs.reject { |dir| eager_load_exclusions.member?(dir) } while dir = queue.shift each_abspath(dir) do |abspath| next if eager_load_exclusions.member?(abspath) if ruby?(abspath) require abspath unless shadowed_files.key?(abspath) elsif dir?(abspath) queue << abspath end end end @eager_loaded = true end end |
#expand_ignored_glob_patterns ⇒ void
This method returns an undefined value.
198 199 200 201 202 |
# File 'lib/zeitwerk/loader.rb', line 198 def # Note that Dir.glob works with regular file names just fine. That is, # glob patterns technically need no wildcards. ignored_paths.replace(ignored.flat_map { |path| Dir.glob(path) }) end |
#ignore(*paths) ⇒ void
This method returns an undefined value.
Configure files, directories, or glob patterns to be totally ignored.
192 193 194 |
# File 'lib/zeitwerk/loader.rb', line 192 def ignore(*paths) mutex.synchronize { ignored.merge((paths)) } end |
#loaded?(cpath) ⇒ Boolean
Says if the given constant path has been loaded.
321 322 323 |
# File 'lib/zeitwerk/loader.rb', line 321 def loaded?(cpath) loaded_cpaths.member?(cpath) end |
#preload(*paths) ⇒ void
This method returns an undefined value.
Files or directories to be preloaded instead of lazy loaded.
179 180 181 182 183 184 185 186 |
# File 'lib/zeitwerk/loader.rb', line 179 def preload(*paths) mutex.synchronize do (paths).each do |abspath| preloads << abspath do_preload_abspath(abspath) if @setup end end end |
#push_dir(path) ⇒ void
This method returns an undefined value.
Pushes ‘paths` to the list of root directories.
165 166 167 168 169 170 171 172 173 |
# File 'lib/zeitwerk/loader.rb', line 165 def push_dir(path) abspath = File.(path) if dir?(abspath) raise_if_conflicting_directory(abspath) root_dirs[abspath] = true else raise ArgumentError, "the root directory #{abspath} does not exist" end end |
#reload ⇒ void
This method returns an undefined value.
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.
276 277 278 279 |
# File 'lib/zeitwerk/loader.rb', line 276 def reload unload setup end |
#setup ⇒ void
This method returns an undefined value.
Sets autoloads in the root namespace and preloads files, if any.
207 208 209 210 211 212 213 214 215 216 217 |
# File 'lib/zeitwerk/loader.rb', line 207 def setup mutex.synchronize do break if @setup non_ignored_root_dirs.each { |root_dir| set_autoloads_in_dir(root_dir, Object) } do_preload @setup = true end end |
#unload ⇒ void
This method returns an undefined value.
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.
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 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/zeitwerk/loader.rb', line 228 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 |realpath, (parent, cname)| if parent.autoload?(cname) parent.send(:remove_const, cname) log("autoload for #{cpath(parent, cname)} removed") if logger else if cdef?(parent, cname) parent.send(:remove_const, cname) log("#{cpath(parent, cname)} unloaded") if logger else # Already unloaded somehow, that is fine. end unloaded_files.add(realpath) if ruby?(realpath) end end unless unloaded_files.empty? $LOADED_FEATURES.reject! { |file| unloaded_files.member?(file) } end autoloads.clear loaded_cpaths.clear lazy_subdirs.clear shadowed_files.clear Registry.on_unload(self) ExplicitNamespace.unregister(self) @setup = false end end |