From: Gregory Seidman Date: 2006-05-17T23:11:10+09:00 Subject: Re: Dynamically modifying modules to avoid namespace collisi On Wed, May 17, 2006 at 09:34:34AM +0900, Logan Capaldo wrote: [...] } One does not require modules, one requires files. One file may have } many modules in it, or none. Regardless one can still 'require' that } file. } } One way to hack something so it gets stuck in a module is: } } module Protect } eval(File.read("path/to/file.rb")) } end } } Then you access all the classes defined in file.rb like: } } Protect::Node.new # etc. This is a great idiom, but it needs to be able to function as a (nearly) drop-in replacement for require. This means that I need to be able to find the file in the search path that require would normally use. Consider the following: def find_require_file(filename) # NEED IMPLEMENTATION HERE end def namespace_get(str) str.to_s.split("::").inject(Object) { |ns,name| ns.const_get(name) } end def require_within(module_name, filename) file = find_require_file(file) mod = module_name case module_name when Module,Class #noop else mod = namespace_get(mod) end mod.instance_eval { eval File.read(file) } end This is untested, and I don't know how to implement that find_require_file, but the idea is that the following should work: module Foo module Bar end end require_within Foo::Bar, "date" x = Foo::Bar::Date.today Anyone want to implement find_require_file and test the idea? --Greg