Wrapped Modules

A

Austin Ziegler

Last night, I was asked about loading objects into a namespace.
Thinking about it, I came up with this:

module Kernel
def require_wrap(resource, mod)
old_lf = $LOADED_FEATURES.dup
topconst = Module.constants
res = require resource

(Module.constants - topconst).each do |const|
mod.__send__:)const_set, const,
Object.__send__:)remove_const, const))
end

$LOADED_FEATURES.replace(old_lf)
ensure
res
end
end

module My; end
module Your; end
require_wrap 'cgi', My
require_wrap 'cgi', Your

puts My::CGI.escape("hello, world")
puts Your::CGI.escape("hello, world")

I don't know if this is useful -- and it has a few drawbacks. First,
I have no clue whether it will work with deep nesting and
references. Second, it won't work on modifications to already
existing classes. Third, the class name is reported as if it were at
the top level.

The better choice to solve the third is to do what Jim Weirich
suggested: read the file as a string and module_eval it.

But I throw this out for discussion in any case.

-austin
 

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,175
Messages
2,570,942
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top