From: Robert Klemme Date: 2011-05-02T03:05:32+09:00 Subject: Re: Why defining a constant in a method is not allowed but using self.class.const_set is allowed? On 01.05.2011 14:36, Iņaki Baz Castillo wrote: > 2011/5/1 Robert Klemme: >>> Humm, yes, having a HASH constant containing a hash is faster than >>> accessing instance variables within a class. Just a bit, but faster :) >> >> You never mentioned a performance problem you are trying to solve. Could be >> that you are worrying too much about an irrelevant detail. > > Yes, I know :) > Yoo much-preoptimization :) Don't. You know what Knuth said about it, do you? >>> So I'll use it, something like: >>> >>> module MyApp >>> CONFIGURATION = {} >>> end >> >> This might be a corner case but I would generally advice to not use global >> variables (or constants) for this. The reason is simply that you loose a >> lot of flexibility. You can only ever have one active configuration at a >> time - and you cannot change it concurrently as well. > > Well, I can change it globaly: Of course. But you need synchronization to make that thread safe. >> It may be OK for a small script or application but if you make that design a >> habit you might run into problems later. Generally it is better to provide >> configuration and other information from the outside because that also makes >> testing easier. You can pass in whatever mock you want to use to test a >> particular feature. If OTOH instances decide themselves where to get the >> information from (i.e. the global variable / constant) you are out of luck >> (or you need to patch methods of the class under test while testing which is >> generally not a good idea because then you don't test any more what will be >> productive eventually). > > I read the configuration from a text file (maybe YAML). But later, for > each request in my server, my classes and methods must access some > configuration fields (for each request), for example the log level. > This is the reason I need such access to be as fast as possible. Passing a configuration via a setter is not really something to worry about speed wise. > Anyhow, I don't want to loose flexibility neither mantain ugly code > (deleting and re-creating constants for each configuration change). > After this thread I hope that using a constant hash (i.e: > MyServer::CONFIGURATION) is a good choice between > ellegancy/flexibility and efficience. Is your code loaded once or is it reloaded for every request? > Thanks a lot for your response. You're welcome! Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/