[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Simple Q: object creation to be determined by incoming data

Brian Candler

5/21/2007 12:02:00 PM

On Mon, May 21, 2007 at 08:38:02PM +0900, Todd Benson wrote:
> I want to do off-the-stream object creation, and
> so I've went and done something like:
>
> instance_eval( "#{class_name_from_stream_chunk}.new( data_from_stream_chunk
> )" )
>
> Is this the only way to do this (by "way", I mean the code and also the
> manner), and if not, the best way?

If the class names are all top-level, e.g. "Foo", then

obj = Object.const_get(classname).new(*args)

If the class names are all under one module, e.g. the string "Foo" really
means Bar::Foo, then

obj = Bar.const_get(classname).new(*args)

(I'd recommend this form, as it prevents your stream creating objects except
those directly under a 'safe' module)

If the class names are arbitary nested modules, e.g. they could be
"Bar::Foo", then

obj = classname.split('::').inject(Object) { |k,c| k.const_get(c) }.new(*args)

This assumes that your data_from_stream_chunk has been split into an array
called 'args' (the 'shellwords' modules is useful for this). And also you
have to make everything the correct type, e.g. if your object expects
an integer constructor then you'll have to call to_i.

HTH,

Brian.