[Ruby] Add support for autload
Created by: brodock
Description
In Ruby there are two ways of loading a Class/Module/Gem. One if by eager loading it with require
, which will also execute any code present in the file outside of a module
or class
block (like other requires or any code at all).
The other (lazy-loaded) is by declaring autoload :ConstantName, 'path/to/file'
. When using autoload, the first time the constant is called (ex: a Module or Class name), the file referred is loaded.
Lazy Loading can improve bootup performance for CLI applications as only used parts are loaded from the disk. In applications with hundreds of files this does make a difference.
It also benefits Rails applications when loading in development mode, as code is loaded from disk only when required (this is what Zeitwerk does for rails-based code, but the principle is the same an can be used for gems). Still in rails land, it can also help lower rake task start time, as those usually touch only parts of the codebase, if we can use lazy-loading effectively, there is less things we need to load from the disk.
There are some cases where autoload may not be fully desired: When using an app server that uses fork
, you may want to eager-load most of the codebase in memory so that when fork
is triggered, you can benefit from sharing that to forked process and rely on CoW.
In case of autoload and fork, this can be mitigated by adding manual requires in a before_fork block in the app server configuration file.
This approach is supported by both Puma and Unicorn.
Suggest a fix/enhancement
Switch from require
approach to autoload
(either by default or as a configuration param).