YAML dumping custom object that needs type conversions

I want to use Ruby 1.8.6 YAML to dump this (simplified) object:

class T < Struct.new(:template)

The :template accessor stores a class, which isn’t something that YAML
can dump. So it seems I need to convert it to a string going out:

def to_yaml(io)

… template.name …

… and then back into a class when it’s read back in:

YAML.add_domain_type('exampler.com,2008', 'T') { | type, val |
     T.new(eval(...something...))
 }

I’ve been using the last solution for <http://rubyquiz.com/
quiz38.html> as a guide, but it turns out that doesn’t work. If you
dump an object of its SProc class, you get this result: “—
\nproc_src: 1+1\n”. And when you read it back in, you get a hash:
{“proc_src”=>“1+1”}

Here’s the code I’d like to see work. Any help appreciated.

require ‘yaml’

class T < Struct.new(:template)
def to_yaml(io)
YAML::quick_emit(self.object_id, io) { |out|
out.map("!exampler.com,2008/T" ) { |map|
map.add(“template”, template.name)
}
}
end
end

YAML.add_domain_type(‘exampler.com,2008’, ‘T’) { | type, val |
T.new(eval("#something#"))
}

d = YAML.dump([T.new(Object)])
puts d.inspect
puts YAML.load(d).inspect

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs