def create(class)
@obj = eval("#{class}.new()")
end
Is there a better way of doing this to avoid the hit of eval()?
Thanks,
-John
@obj = Object.const_get(klass).new
Using "class" as a parameter name won't work - the standard is to use
"klass" instead.
Bill
--
Bill Atkins
My fault for typing class as the parameter name - that's what I get for
typing code frags from scratch without running them first in a language
I've been using for 12 hours :)
If you're working with Rails, or just have the Active Support gem
available, this pattern has been boiled down to
klass.constantize.new().
--
David Heinemeier Hansson,
http://www.basecamphq.com/ -- Web-based Project Management
http://www.rubyonrails.org/ -- Web-application framework for Ruby
http://www.loudthinking.com/ -- Broadcasting Brain
does this work if klass == My::Namespace::Klass ?
-g.
Assuming you mean the string value
klass = "My::Namespace::Klass"
The answer is No. One has to do:
klass = "Klass"
@obj = My::Namespace.const_get(klass).new
The namespace issue is problematic. One alternative is in Ruby Facets:
require 'facet/object/constant'
klass == "My::Namespace::Klass"
@obj = constant(klass).new
T.
I was expecting the negative answer ;-)
> One alternative is in Ruby Facets
Interesting, I 'll see how that works...
-g.
Or the ever popular
klass.split('::').inject(Object) {|parent, name| parent.const_get(name)}