Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Module#autoload_relative
static VALUE
rb_mod_autoload_relative(VALUE mod, VALUE sym, VALUE file)
{
ID id = rb_to_id(sym);
VALUE base, absolute_path;
FilePathValue(file);
base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath (autoload_relative called without file context)");
}
base = rb_file_dirname(base);
absolute_path = rb_file_absolute_path(file, base);
rb_autoload_str(mod, id, absolute_path);
return Qnil;
}
Registers filename to be loaded (using Kernel::require) the first time that const (which may be a String or a symbol) is accessed in the namespace of mod. The filename is interpreted as relative to the directory of the file where autoload_relative is called.
module A end A.autoload_relative(:B, "b.rb")
If const in mod is defined as autoload, the file name to be loaded is replaced with filename. If const is defined but not as autoload, does nothing.
The relative path is converted to an absolute path, which is what will be returned by Module#autoload? for the constant.
Raises LoadError if called without file context (e.g., from eval).
Ruby version changes
-
4.1
-
Kernel#autoload_relativeandModule#autoload_relativeare added. These methods work likeautoload, but resolve the file path relative to the file where the method is called, similar torequire_relative. This makes it easier to autoload constants from files in the same directory without hardcoding absolute paths or manipulating$LOAD_PATH. [Feature #15330]
-