End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Module#const_missing
mod.const_missing(sym) → obj
object.c
View on GitHub ↗
VALUE
rb_mod_const_missing(VALUE klass, VALUE name)
{
VALUE ref = GET_EC()->private_const_reference;
rb_vm_pop_cfunc_frame();
if (ref) {
rb_name_err_raise("private constant %2$s::%1$s referenced",
ref, name);
}
uninitialized_constant(klass, name);
UNREACHABLE_RETURN(Qnil);
}
Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant, and returns a value to be used for that constant. The following code is an example of the same:
Example
def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
In the next example when a reference is made to an undefined constant, it attempts to load a file whose name is the lowercase version of the constant (thus class Fred is assumed to be in file fred.rb). If found, it returns the loaded class. It therefore implements an autoload feature similar to Kernel#autoload and Module#autoload.
Example
def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end
See also
#const_get
#const_set
#const_defined?
#const_source_location
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0