T. Onoma
1/17/2005 12:05:00 PM
Or try Ruby Facets:
require 'facet/object/constant'
class Builder
def Builder.create( klass, *data )
constant( klass ).new( *data )
end
end
T.
P.S. I debate with myself that the method might be better place in Kerenl, so
it might move there in future.
On Monday 17 January 2005 06:42 am, Peter Hickman wrote:
| Luc Heinrich wrote:
| >Peter Hickman <peter@semantico.com> wrote:
| >> return klass.new(data)
| >
| >return Kernel.const_get(klass).new(data)
| >
| >Note that const_get will throw an exception if the passed class name is
| >unknown, so be prepared to deal with that.
|
| Actually, trying to catch the error seems to be harder than it should
| be. For example:
|
| class Builder
| def Builder.create( klass_sym, data )
| begin
| return Kernel.const_get( klass_sym ).new( data )
| rescue
| raise "There was an error"
| end
| end
| end
|
| Should report "There was an error" when const_get fails. However this is
| untrapped.
|
| xx.rb:26:in `const_get': uninitialized constant Bernie at Kernel
| (NameError) from xx.rb:26:in `create'
| from xx.rb:43
|
| I've tried splitting this up into individual steps:
|
| x = Kernel.const_get( klass_sym )
| x.new( data )
|
| but this makes no difference.