From: Joel VanderWerf Date: 2005-07-03T04:35:38+09:00 Subject: Re: Loading a file without cluttering the global namespace Benjamin Hepp wrote: > Hello, > > I'm trying to build a module-mechanism in ruby so that I am able to load a > ruby-file without cluttering up the global namespace of the program. > > For example I want to be able to load a ruby-file, search for methods in > it, possibly execute one of them and then "unload" the file. When I call > Kernel#load with wrap = true, everything of the new file is put into an > anonymous Module, but every other file loaded in the new file itself is > put into the global namespace again. > > My questions: > > Is it at all possible to prevent this? If so, how to do it? > Can I access the anonymous Module in an easy manner? > How to delete/undefine a class or a method? A partial answer is the script library: http://raa.ruby-lang.org/project/script It cannot unload a library, and it cannot change what namespace .so extensions put their definitions in, but: * It wraps a loaded file (and its "local dependencies") in an instance of the Script class, which is a subclass of Module. * You can then assign this Script instance to a local var, constant, or whatever: script = Script.load("my-script.rb") * Top level method defs and constant defs in the wrapped file(s) can be accessed as methods or constants of this instance: script.foo() script::Foo * The "local dependencies" are defined to be any .rb files that can be found relative to the dir of the main script. This is handled by redefining #load and #require in the context of the Script instance. If the specified path is not found locally (or is a .so), then it falls back to Kernel#require. * There's also an autoloading feature. And there's another library to do this kind of thing: http://codeforpeople.com/lib/ruby/dynaload/