const lookup, autoloading, and scoping

S

Steven Parkes

I'm trying to do nested class/module lookup by name and beginning to =
think it's not possible/clean in the face of autoloading.

The lookup is typical/simple String =3D> Module:

cls =3D cls.split("::").inject(Object) {|scope, const_name| =
scope.const_get(const_name)}

Trouble arrises when you use autoloading (the nested names aren't =
already defined) and someone creates a class of the same name at the top =
level/Object scope. In that case, the const_get will resolve to the top =
level rather than loading the nested object. (Actually, it'll occur if =
anyone creates a class of the same name in any parent ...)

Alternatives seem to be:
- don't use autoloading
- eval a string to get the class (not sure if this even works)
- unique-ify all your class names everywhere, not just per-scope

Am I missing anything?
 
I

Intransition

I'm trying to do nested class/module lookup by name and beginning to thin=
k it's not possible/clean in the face of autoloading.
The lookup is typical/simple String =3D> Module:

=A0 =A0 cls =3D cls.split("::").inject(Object) {|scope, const_name| scope= const_get(const_name)}

Trouble arrises when you use autoloading (the nested names aren't already=
defined) and someone creates a class of the same name at the top level/Obj=
ect scope. In that case, the const_get will resolve to the top level rather=
than loading the nested object. (Actually, it'll occur if anyone creates a=
class of the same name in any parent ...)
Alternatives seem to be:
- don't use autoloading
- eval a string to get the class (not sure if this even works)
- unique-ify all your class names everywhere, not just per-scope

Am I missing anything?

It looks to me that you have made a good point. The only solution is
to use eval instead (it should work). I may have to take this into
account myself with a method in Ruby Facets --it never occurred to me
that autoload would fail against such code. Actually, some example
code demonstrating the issue would be nice. Does it only occur when
the toplevel constant has been defined by another lib?

Of course, autoload still has another (and imho) more serious issue.
It doesn't respect customized require methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,366
Latest member
IanCulpepp

Latest Threads

Top