# YAML dumping custom object that needs type conversions

**URL:** <https://www.ruby-forum.com/t/yaml-dumping-custom-object-that-needs-type-conversions/146332>\
**Category:** Ruby\
**Created:** [August 20, 2008, 1:49am UTC](https://www.ruby-forum.com/t/yaml-dumping-custom-object-that-needs-type-conversions/146332 "2008-08-20T01:49:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![bdmcnitt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/a4c791/32.png) [@bdmcnitt](https://www.ruby-forum.com/u/bdmcnitt)\
**Post date:** [August 20, 2008, 1:49am UTC](https://www.ruby-forum.com/t/yaml-dumping-custom-object-that-needs-type-conversions/146332/1 "2008-08-20T01:49:32Z")

</div>

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/](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](http://exampler.com),2008/T” ) { |map|  
map.add(“template”, template.name)  
}  
}  
end  
end

YAML.add\_domain\_type(‘[exampler.com](http://exampler.com),2008’, ‘T’) { | type, val |  
T.new(eval(“#something#”))  
}

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