On Tue, 13 Mar 2007 15:47:13 +0100, Matteo Cavalleri wrote:

> I need to create some objects of different (custom) classes, in
> different pages of my site, so I made some code that takes an array of
> hashes and create the objects. the hashes are like this one:
> 
> h = { :class => Class1, :param1 => 'foo', :param2 => 'bar', etc }
> 
> and basically I do
> 
> object = h[:class].new(h)
> 
> everything works fine as long as the hash is defined inside the source
> code. however in some case I need to create the same object in two
> different file. to avoid writing the same hashes twice I though about
> putting them in a YAML file but this method doesn't work anymore because
> the class name is converted to a string instead of a reference to the
> class, using !ruby/object creates the object but all the code inside the
> initialize method seems to be never executed (or the instance variables
> ovverrided after the inzialize method) so my objects don't work,
> ClassName.to_yaml returns an error, etc...
> 
> is there a way to do what I want to do? putting the ashes in a file and
> loading them as a source AFAIK creates other problem due to the
> sandboxing made by mod_ruby, that's why I tried with yaml.

If you reference the class object directly, you can't dump it to yaml, so 
try using a string instead, and running eval on the string to get the 
class object.

h = { :class => 'Class1', :param1 => 'foo', :param2 => 'bar', etc }
object = eval(h[:class]).new(h)

This gives you the following YAML:
--- 
:class: Class1
:param1: foo
:param2: bar

-- 
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/