Creating objects using strings

hi

I’m new to ruby and this list, so please forgive me if this is a silly
question but:

Is it possible to create an object of a specific type when all I have is the
name of the class in a string?

I’m wanting to serialize objects to XML, but I need to have the type
information stored in the XML and create objects of a type based on that
information. I have looked at the clxmlserial library but it needs to know
the type when re-creating objects. I have tried making a class
XmlSerializableObject with _dump and _load methods for use with Marshal, but
the type information is still stored in a non-xml format at the start of the
file. Do I need to write a module in c to do this?

Any help would be greatly appreciated,

···


George Mochrie
aka Drasil
ICQ# 84423409

Is it possible to create an object of a specific type when all I have is the
name of the class in a string?

a class is stored in a constant, if you have its name you can retrieve the
associated constant with #const_get

For example

pigeon% ruby -e 'klass = "Array"; p Object.const_get(klass).new'

pigeon%

Guy Decoux

George Mochrie wrote:

Is it possible to create an object of a specific type when all I have is the
name of the class in a string?

There’s a page on the Wiki on this:

Cheers

Dave

George Mochrie wrote:

Is it possible to create an object of a specific type when all I have is
the name of the class in a string?

There’s a page on the Wiki on this:

http://www.rubygarden.org/ruby?FindClassesByName

I know we’ve been through this before, but I thought I’d repeat it
anyway. I have a slightly more robust version, called String#to_class,
which handles periods, “relative” class paths, and anonymous namespaces.

Check it out at http://www.pablotron.org/download/string_to_class.rb.

PS I wasn’t quite sure where to put this on the Wiki page. Before the
simple example? After it? Not at all? Dave?

···

Cheers

Dave


Paul Duncan pabs@pablotron.org pabs in #gah (OPN IRC)
http://www.pablotron.org/ OpenPGP Key ID: 0x82C29562

If it’s a big chunk and you don’t want to interfere with what’s
already there, then put it on a second page and add a link to the
“main” page.

Since this is like a “refactoring” of the wiki page, then a subpage
would probably be appropriate, like

FindClassByName/ImplementationExample

This can be referenced as “/ImplementationExample” in the
FindClassByName page.

The wiki will be richer for your contribution :slight_smile:

Gavin

···

On Thursday, February 13, 2003, 9:24:10 AM, Paul wrote:

Check it out at http://www.pablotron.org/download/string_to_class.rb.

PS I wasn’t quite sure where to put this on the Wiki page. Before the
simple example? After it? Not at all? Dave?