Method: Module#const_missing
- Defined in:
- variable.c
#const_missing(sym) ⇒ Object
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. For example, consider:
def Foo.const_missing(name)
name # return the constant name as Symbol
end
Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
As the example above shows, const_missing is not required to create the
missing constant in mod, though that is often a side-effect. The
caller gets its return value when triggered. If the constant is also defined,
further lookups won't hit const_missing and will return the value stored in
the constant as usual. Otherwise, const_missing will be invoked again.
In the next example, when a reference is made to an undefined constant,
const_missing attempts to load a file whose path is the lowercase version
of the constant name (thus class Fred is assumed to be in file
fred.rb). If defined as a side-effect of loading the file, the
method returns the value stored in the constant. This implements an autoload
feature similar to Kernel#autoload and Module#autoload, though it differs in
important ways.
def Object.const_missing(name)
@looked_for ||= {}
str_name = name.to_s
raise "Constant not found: #{name}" if @looked_for[str_name]
@looked_for[str_name] = 1
file = str_name.downcase
require file
const_get(name, false)
end
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 |
# File 'variable.c', line 2341 VALUE rb_mod_const_missing(VALUE klass, VALUE name) { rb_execution_context_t *ec = GET_EC(); VALUE ref = ec->private_const_reference; rb_vm_pop_cfunc_frame(); if (ref) { ec->private_const_reference = 0; rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name); } uninitialized_constant(klass, name); UNREACHABLE_RETURN(Qnil); } |