Project

General

Profile

Actions

Feature #19633

open

Allow passing block to `Kernel#autoload` as alternative to second `filename` argument

Added by shioyama (Chris Salzberg) 12 months ago. Updated 12 months ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:113430]

Description

Kernel#autoload takes two arguments, a symbol module representing the constant to be autoloaded, and a filepath to load the constant from (with require).

Currently, Zeitwerk has to monkeypatch Kernel#require to fetch the loader for the file being loaded, then run the original (aliased) require, then run autoload callbacks. In addition to the monkeypatch, this also requires a registry (Zeitwerk::Registry) to map file paths to loaders, to know which loader should be used for a given autoload-triggered require. In fact, Zeitwerk has to assume that the monkey-patched require call came from an autoload trigger; there is no way to really be sure of the source.

If Ruby allowed passing a block as an alternative to the explicit filepath, then I think this could be improved and would eliminate the need for a monkeypatch. So something like this:

autoload(:B) do
  require "lib/b"
  # trigger callback, etc
end

I am implementing a gem called Im which is a fork of Zeitwerk, and in the case of this gem, such a feature would be even more useful. Im implements autoloads on anonymous modules by registering an autoload and then "catching" the require and converting it into a load, passing the module as the second argument (see here.) This is currently quite tricky because, again, it's hard to know where a require came from.

In addition to removing the monkeypatch (inherited from Zeitwerk), Im would further benefit from the block argument because then it could simply access the module via a closure, rather than pulling it from a registry:

mod.autoload(:Foo) do
  load "lib/foo.rb", mod
end

I don't know how hard or easy this would be to implement, but if there is interest in this as a feature I'd be happy to look into implementing it.

Actions

Also available in: Atom PDF

Like1
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0