YAML dumping custom object that needs type conversions

B

Brian Marick

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top