YAML-ing classes and modules in 1.8.4 -- Was: Re: Extend an object with module stored
- From: Joel VanderWerf <vjoel@xxxxxxxxxxxxxxxxx>
- Date: Wed, 1 Feb 2006 04:48:42 +0900
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
.
- References:
- Extend an object with module stored
- From: Andrea Reginato
- Re: Extend an object with module stored
- From: Joel VanderWerf
- Extend an object with module stored
- Prev by Date: Re: Looking for web crawler written in Ruby
- Next by Date: Re: ri bug?
- Previous by thread: Re: Extend an object with module stored
- Next by thread: Re: Extend an object with module stored
- Index(es):
Relevant Pages
|