From: Rick DeNatale Date: 2009-04-02T01:09:09+09:00 Subject: Re: Anything better than klass = eval("#{task_class}") --0016361648b35c5cad0466808af0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Wed, Apr 1, 2009 at 10:47 AM, Rob Biedenharn wrote: > On Apr 1, 2009, at 9:32 AM, Gregory Brown wrote: > > On Wed, Apr 1, 2009 at 9:14 AM, Paganoni wrote: >> >>> Hi, well subject is self explanatory... >>> >>> Seems a bit to verbose for me but I don't know any other solution to >>> convert >>> a string containing a class name to a constant of that class name... >>> Excepted rails way : task_class.camelize.constantize which is verbose >>> too... >>> >> >> Object.const_get("String") >>>> >>> => String >> >> -greg >> >> -- >> BOOK: http://rubybestpractices.com >> TECH: http://blog.majesticseacreature.com >> NON-TECH: http://metametta.blogspot.com >> > > Or dealing with things like Admin::User or Net::HTTP > > # from Jim Weirich (based on email correspondence) > def constantize(camel_cased_word) > camel_cased_word. > sub(/^::/,''). > split("::"). > inject(Object) { |scope, name| scope.const_get(name) } > end > > It may be more verbose, but it is much safer that plain 'ole eval() > Actually, I don't think this is entirely right, since const_get will find constants found in outer scopes. For example constantize("MyModule::Object") would return ::Object So a little better would be: def constantize(camel_cased_word) camel_cased_word. sub(/^::/,''). split("::"). inject(Object) { |scope, name| scope.const_defined?(name) ? scope.const_get(name) : scope.const_missing(name) } end -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale --0016361648b35c5cad0466808af0--