From: Robert Klemme Date: 2009-11-18T05:20:55+09:00 Subject: Re: Class inside a Method Body On 17.11.2009 19:40, Marnen Laibow-Koser wrote: > Mike Stephens wrote: >> My concern here is when you use libraries. When your user just wants to >> get a list of product categories from the web server, you seem to risk >> Ruby parsing the whole portfolio of library capabilities despite the >> fact you emphatically won't use 99% of them on that transaction. > > Not at all. This is what require is for. If you don't require a file, > it won't be read. Mike's point is, that if you require a library which requires other files in turn you might end up loading 50 files although you just need 3 of them. That overhead can be significant for short lived programs. He has a valid point: basically his question is, how do I declare file dependencies in complex libraries without immediately "executing" them (means: reading all those files)? A good approach here is to use autoload alone or a combination of autoload and require as I have done in the Muppet Laboratories project (see link below). >> Autoload does look as though it addresses this. > > Autoload just automates require AFAIK. Yes, but this is crucial here: autoload will require a file once a constant is accessed the first time. And you can even nest it, i.e. use it inside a module. That way, if a class is never used at all, you won't read that file. You can find an example in my project: http://github.com/rklemme/muppet-laboratories/blob/master/lib/animal.rb >> The other solution you mentioned was you put require inside a method and >> then Ruby won't execute it until control passes to the method, so if you >> don't need that method, you don't incur the cost of interpreting it. >> Presumably you can't add classes this way > > Of course you can! Why do you think you can't? Exactly. The required file can contain anything - from zero to multiple classes. >> and, from a glance at The Ruby >> Programming Language (Flanagan & Matsumoto), there is a risk the >> included code gets treated as belonging to a different scope to the >> calling method (although that might be a plus point). > > If you wrap it in a class or module, you get to specify the scope. Hmm... I am not aware of any scoping issues right now but you could avoid them by anchoring the class name: class ::Foo end That class is always defined in the root namespace. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/