Namespace conflict resolution

D

Dema

Hi guys,

This question is better explained with an example:

I have the standard File class, right? Suppose I define another File
class within my own namespace:

module MyNamespace
class File
...
end
end

Now, if I am on an irb session and I want to refer to my
MyNamespace::File class using only the short form 'File', I would do:
include MyNamespace

How does Ruby decide which class to use when I reference 'File' in this
scope? (I've already tested and the original 'File' class is the chosen
class)

How would I be able to temporarely replace the standard 'File' class in
the global Object namespace with my own File class and then revert it
back to the standard when I'm done?

rgds
Dema
http://dema.ruby.com.br
 
D

Daniel Berger

Dema said:
Hi guys,

This question is better explained with an example:

I have the standard File class, right? Suppose I define another File
class within my own namespace:

module MyNamespace
class File
...
end
end

Now, if I am on an irb session and I want to refer to my
MyNamespace::File class using only the short form 'File', I would do:
include MyNamespace

How does Ruby decide which class to use when I reference 'File' in this
scope? (I've already tested and the original 'File' class is the chosen
class)

How would I be able to temporarely replace the standard 'File' class in
the global Object namespace with my own File class and then revert it
back to the standard when I'm done?

rgds
Dema
http://dema.ruby.com.br

My general response would be: don't do that. My personal experience is
that slapping existing Ruby classes under your own namespace is a bad
idea. It's just a pain. The fact that you're trying to use the "short
form" only reinforces that it's unnecessary.

Just put your methods directly in the File class without the added
namespace.

Regards,

Dan
 
D

Dema

Unfortunately, I can't do that.

Both the class definitions and the code that's going to use the short
form of the classes are evaluated during runtime, so it's basically a
environment where the power user can define and use new classes.

I want this runtime evaluation to occur in a sandbox, without
interference or conflicts from the standard class names, but I don't
want to obligate the user to use the long names for the namespaced
classes.

I hope I am being clear here.

rgds
Dema
 
G

Gennady Bystritksy

You can evaluate the code to be run in a sandbox in the binding of a
module you defined your own File class in (see eval, module_eval). To
refer to a standard class you will have to use ::File from there.

Gennady.
 

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
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top