Joel VanderWerf
1/31/2006 7:49:00 PM
Joel VanderWerf wrote:
> I had some code to serialize module and class identities (without any of
> their instance variables or class variables, though) with 1.8.2 (see
> below) but it seems not to work with 1.8.4. I will take a look at it
> later today.
Here's a version for 1.8.4. Are you listening, _why, and is there a
chance of putting this in the YAML lib?
----------------------------------
Sample code:
----------------------------------
yy = [Enumerable, Comparable, String, File].to_yaml
puts yy
p YAML.load(yy)
----------------------------------
Output:
----------------------------------
---
- !ruby/module Enumerable
- !ruby/module Comparable
- !ruby/class String
- !ruby/class File
[Enumerable, Comparable, String, File]
----------------------------------
Implementation:
----------------------------------
require 'yaml'
class Module
yaml_as "tag:ruby.yaml.org,2002:module"
def Module.yaml_new( klass, tag, val )
if String === val
val.split(/::/).inject(Object) {|m, n| m.const_get(n)}
else
raise YAML::TypeError, "Invalid Module: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) { |out|
out.scalar( "tag:ruby.yaml.org,2002:module", self.name, :plain )
}
end
end
class Class
yaml_as "tag:ruby.yaml.org,2002:class"
def Class.yaml_new( klass, tag, val )
if String === val
val.split(/::/).inject(Object) {|m, n| m.const_get(n)}
else
raise YAML::TypeError, "Invalid Class: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) { |out|
out.scalar( "tag:ruby.yaml.org,2002:class", self.name, :plain )
}
end
end
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407