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.

It is possible to extend YAML to serialize classes:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/177604

It seems to still work with ruby-1.8.6.

It lets you do this:

yy = [Enumerable, Comparable, String, File].to_yaml
puts yy
p YAML.load(yy)

with output:

---
- !ruby/module Enumerable
- !ruby/module Comparable
- !ruby/class String
- !ruby/class File
[Enumerable, Comparable, String, File]

However, if you are hand-editing the YAML file, you may find that a 
class name string is more convenient than this notation.

YYAMLMMV

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407