Permalink
Browse files

Added ClassMethods#const_defined? to attempt loading constants.

  • Loading branch information...
1 parent 6a8c8ab commit 50d44c4bf170ad785af5a7cb0c8e6e1aa5026c36 @postmodern committed Nov 20, 2011
@@ -79,6 +79,27 @@ def require_file(name)
return true
end
+ #
+ # Checks if a constant is defined or attempts loading the constant.
+ #
+ # @param [String] name
+ # The name of the constant.
+ #
+ # @return [Boolean]
+ # Specifies whether the constant is defined.
+ #
+ def const_defined?(name)
+ if super(name)
+ true
+ else
+ # attempt to load the file that might have the constant
+ require_file(OpenNamespace.const_path(name))
+
+ # check for the constant again
+ return super(name)
+ end
+ end
+
#
# Finds the exact constant.
#
@@ -159,18 +180,9 @@ def const_search(file_name)
# @see require_const.
#
def const_missing(name)
- file_name = OpenNamespace.const_path(name)
-
- if require_file(file_name)
- #
- # If const_missing is being called, the constant is not present yet.
- # Therefor, only check for the constant if the file was
- # successfully loaded by require_file.
- #
- if self.const_defined?(name)
- # get the exact constant name that was requested
- return self.const_get(name)
- end
+ if self.const_defined?(name)
+ # get the exact constant name that was requested
+ return self.const_get(name)
end
return super(name)
@@ -0,0 +1,6 @@
+module Classes
+ module CustomNamespace
+ class ConstantThree
+ end
+ end
+end
@@ -0,0 +1,6 @@
+module Classes
+ module SimpleNamespace
+ class ConstantThree
+ end
+ end
+end
@@ -66,6 +66,10 @@
const.should be_nil
end
+ it "should attempt loading the constant when calling const_defined?" do
+ @module.const_defined?('ConstantThree').should == true
+ end
+
it "should load constants transparently via const_missing" do
const = @module::ConstantTwo
@@ -136,6 +140,10 @@
const.should be_nil
end
+ it "should attempt loading the constant when calling const_defined?" do
+ @module.const_defined?('ConstantThree').should == true
+ end
+
it "should load constants transparently via const_missing" do
const = @module::ConstantTwo

0 comments on commit 50d44c4

Please sign in to comment.