From 52607877c68f2c405dac50a13d5b73d35825c585 Mon Sep 17 00:00:00 2001 From: drbrain Date: Thu, 16 Jun 2011 06:17:59 +0000 Subject: * variable.c (const_missing): Add simple example of const_missing. Patch by Anuj Dutta. [Ruby 1.9 - Bug #4794] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@32120 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- variable.c | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) (limited to 'variable.c') diff --git a/variable.c b/variable.c index 426d58f23e..7ea63f03e4 100644 --- a/variable.c +++ b/variable.c @@ -1370,27 +1370,35 @@ const_missing(VALUE klass, ID id) * call-seq: * 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. + * 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: * - * 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 + * 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. + * + * 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 * */ -- cgit v1.2.3