From: Robert Klemme Date: 2010-08-31T15:15:10+09:00 Subject: Re: require from a method On 08/29/2010 03:34 PM, Jörg W Mittag wrote: > Markus Fischer wrote: >> On 29.08.2010 12:40, Robert Klemme wrote: >>> On 29.08.2010 12:25, Ammar Ali wrote: >>>> Are there any gotchas in requiring files from within a method? It >>>> seems to work, but I have a sinking feeling that I'm missing something >>>> here. >>> Not technically. It might even be more efficient if you require a >>> particular functionality only rarely and include the "require" in the >>> method that needs that functionality. >> Sorry for hijacking, but I'm wondering how require exactly works in the >> context of a class or method; does scoping play any role if I've defined >> classes/modules in the required file? > > No. Required files always get evaluated in the global context. Which > is actually another gotcha: if you call require inside a module or > class, then it *looks like* you jail the library into a namespace, > when in fact you don't. Code that looks like it's doing one thing, but > does another thing, is always dangerous. Which is one good reason for not doing it at all. :-) > Note that Kernel#load takes an optional boolean argument telling it to > load the file into an anonymous module instead of the global > namespace. (Unfortunately, there doesn't seem to be any way to > actually *get* at that module[1], so this API looks rather useless. > Also, the code in that file can always use ::Object to gain access to > the global namespace.) > > jwm > > [1] except for ugly hacks with ObjectSpace The usage of load with module I can think of is to load a file which registers instances or classes somewhere in some kind of global registry (hence you need global scope access). That way you do not have to care how everybody names their classes and they don't interfere with each other - which is good for this plugin like scenario. But I agree, more direct access to the scope used would increase utility of that feature a lot. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/