From: Robert Klemme Date: 2006-03-23T22:48:52+09:00 Subject: Re: Is this a kind of design patterns? Jim Weirich wrote: > Robert Klemme wrote: >> IMHO this is not thread safe. If you need the method interface, you >> could do something like > [...] >> :-) > > I did catch the smiley. :) :-) > Given that the original returned a new object on every invocation, a > race condition that might generate an extra light weight object or two > at initialization seems to be a low risk. > > However, if I were really concerned about the race condition, I think I > would go the metaprogramming route rather then the dynamic lookup route. > Something more like this: > > class Color > ... > class << self > private > def define(name, color) > class_eval "#{name.to_s.upcase} = color" > class_eval "def Color.#{name}; #{name.to_s.upcase}; end" > end > end > > define :red, Color.new(255, 0, 0) > ... > end > > ;) :-) Since we're in Color anyway, you can simplify the definition that by class Color # ... class << self private def define(name, *args) cname = name.to_s.upcase col = const_set( cname, new(*args)) class_eval "def self.#{name}; #{cname}; end" end end define :red, 255, 0, 0 # ... end :-) Kind regards robert