How to pick up the loader in a different file
HoneyryderChuck opened this issue ยท 2 comments
Hi ๐
I'm looking at integrating zeitwerk in a plugin for a gem I'm building. The idea is, while the app itself defines the loader, the dirs, etc, the plugin integrates the reloading in its "loop".
The doc mentions the following:
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.
You can reload if you want to:
loader = Zeitwerk::Loader.new
loader.push_dir(...)
loader.enable_reloading # you need to opt-in before setup
loader.setup
...
loader.reload
But it's not very clear to me how can I pick up the loader in a different file. How does it work exactly?
I assume loader = Zeitwerk::Loader.new
will just instantiate a new object. How could I fetch a loader from the registry?
Hey! You need to store the loader in a globally accessible way, and make that public interface (or, at least, public interface for the plugins).
For example, Rails has two instances, one has reloading enabled, and the other one does not. They are available as
Rails.autoloaders.main
Rails.autoloaders.once
respectively. They are instantiated very early when Rails boots. You can configure loaders gradually, and all has to be in place when setup
is called. In Rails, that happens late so that you can tweak stuff in different phases of the boot process.
That is the idea, you instantiate the loader early, and have it visible as a global property, constant, or even global variable if you wish.
You're right, in the end I managed to find a similar workaround for my use case, that worked better than what I was asking for. Thx for the direction!