Issue #11415 has been reported by Matthew Draper.

----------------------------------------
Feature #11415: autoload with a Proc
https://bugs.ruby-lang.org/issues/11415

* Author: Matthew Draper
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
`autoload` currently allows you to run arbitrary code when a constant is referenced, as long as that code is written to a file.

I propose extending `autoload` to also accept a Proc in place of the string filename.


Usage:

    autoload :Foo, -> { ::Object.const_set :Foo, 42 }
    autoload :Bar, -> { require "bar_1"; require "bar_2" }
    autoload :Baz, -> { with_special_lock { require "baz" } }


No built-in concurrency protection is provided: if a second thread encounters a constant reference before the first one sets the constant, the second thread will also enter the Proc.

Under simple usage, the proc will still call require at some point -- then require's locking will take effect. A more advanced user can apply their own locking.


I believe this is sufficient to allow the Rails dependency loader to use autoload instead of const_missing, and fix the "nested constants" problem.


The implementation is quite small, and it doesn't seem to make the dangers of autoload any worse than they already are. Hopefully, it can provide an easier place for users to experiment in ways to save autoload by making it more generally safe.



*Alternatives*

For Rails's purposes, nested constants could also be solved by a `missing_constant` (or similar) macro:

    module Foo; end
    module Bar; end
    
    Foo::Bar # => returns ::Bar


    module Foo; missing_constant :Bar; end
    module Bar
    
    Foo::Bar # => invokes Foo.const_missing(:Bar)




More directly, instead of passing a Proc to autoload, a caller can write the code to a tempfile, and then specify that tempfile's path.

---Files--------------------------------
autoload-proc.patch (5.83 KB)


-- 
https://bugs.ruby-lang.org/