public Method

Module.const_missing(p1)

mod.const_missing(sym)     obj

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 a (very bad) example: if 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 value of the loaded class. It therefore implements a perverse kind of autoload facility.

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

Source Code

/*
* call-seq:
*    mod.const_missing(sym)    => obj
*
*  Invoked when a reference is made to an undefined constant in
*  <i>mod</i>. It is passed a symbol for the undefined constant, and
*  returns a value to be used for that constant. The
*  following code is a (very bad) example: if reference is made to
*  an undefined constant, it attempts to load a file whose name is
*  the lowercase version of the constant (thus class <code>Fred</code> is
*  assumed to be in file <code>fred.rb</code>). If found, it returns the
*  value of the loaded class. It therefore implements a perverse
*  kind of autoload facility.
*  
*    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
*  
*/

VALUE
rb_mod_const_missing(klass, name)
   VALUE klass, name;
{
   ruby_frame = ruby_frame->prev; /* pop frame for "const_missing" */
   uninitialized_constant(klass, rb_to_id(name));
   return Qnil;		/* not reached */
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.