YAML-ing classes and modules in 1.8.4 -- Was: Re: Extend an object with module stored



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


.



Relevant Pages

  • Re: Tutorial challenge program help
    ... Until then, you learn about instance variables and OOP, it would probably be ... puts "HUH?! ... local variable with the and then compare that input to ... To embed something in a string, you have the opening and closing " symbols, ...
    (comp.lang.ruby)
  • Re: question about assigning null to a reference object
    ... Lew, ... the same language as everyone here. ... String x = b.title; ... the methods and instance variables associated with the reference variable c ...
    (comp.lang.java.help)
  • Re: aargh! this SHOULD be easy!
    ... it says "hi there bob!" ... If these are not instance variables, ... problems because when the source string changed, ... this was in an array of strings not a string itself (like a command queue) ...
    (comp.sys.mac.programmer.help)
  • Re: Runtime.exec(cmd) hangs up
    ... |> | StreamGobbler(InputStream is, String type){ ... |> assign its stdout / stderr instance variables with the stream gobbler ... | StreamGobbler as I am producing the output in those two thrads. ...
    (comp.lang.java.programmer)