Actually, I don't think this is entirely right, since const_get will
find
constants found in outer scopes.
For example constantize("MyModule::Object") would return ::Object
So a little better would be:
def constantize(camel_cased_word)
camel_cased_word.
sub(/^::/,'').
split("::").
inject(Object) { |scope, name| scope.const_defined?(name) ?
scope.const_get(name) : scope.const_missing(name) }
end
--
Rick DeNatale
Blog:
http://talklikeaduck.denhaven2.com/
Twitter:
http://twitter.com/RickDeNatale
WWR:
http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn:
http://www.linkedin.com/in/rickdenatale
irb> # from Jim Weirich (based on email correspondence)
?> def constantize(camel_cased_word)
irb> camel_cased_word.
?> sub(/^::/,'').
?> split("::").
?> inject(Object) { |scope, name| scope.const_get(name) }
irb> end
=> nil
irb> constantize("MyModule::Object")
NameError: uninitialized constant MyModule
from (irb):6:in `const_get'
from (irb):6:in `constantize'
from (irb):8:in `inject'
from (irb):3:in `each'
from (irb):3:in `inject'
from (irb):3:in `constantize'
from (irb):8
from :0
irb> def constantize(camel_cased_word)
irb> camel_cased_word.
?> sub(/^::/,'').
?> split("::").
?> inject(Object) { |scope, name| scope.const_defined?
(name) ? scope.const_get(name) : scope.const_missing(name) }
irb> end
=> nil
irb> constantize("MyModule::Object")
NameError: uninitialized constant MyModule
from (irb):14:in `constantize'
from (irb):16:in `inject'
from (irb):11:in `each'
from (irb):11:in `inject'
from (irb):11:in `constantize'
from (irb):16
from :0
Except for the slight difference in the backtrace, it looks the same
to me. Why do you think it will return Object for
constantize("MyModule::Object") ?
-Rob
Rob Biedenharn
http://agileconsultingllc.com
(e-mail address removed)