Yaml: custom saving and loading of specific classes


I’m trying to use ruby’s yaml library to serialise and deserialise some
legacy classes. Simply adding a to_yaml_properties() method isn’t
sufficient as special methods need to be called to get and set the
properties (they’re not stored simply in instance variables that I can
access), and I don’t want to change the class any more than I have to.
Can anyone offer any pointers on how to get some custom code executed
when an instance of such a class is serialised and deserialised? What
I’d like to do is, when I call YAML.dump(), and it sees an instance of
the legacy class, to convert it into some data structure and dump that,
and do the reverse on YAML.load(). I’m guessing I can do part of this
with the to_yaml() function, but I haven’t been able to find an adequate
reference anywhere. I’d really appreciate any help anyone could give
me. Thanks.