YAML serialization of modules

I know _why is away for a bit, but maybe someone else can shoot down
this idea :slight_smile: Let’s serialize modules with this code:

···

require ‘yaml’

class Module
def is_complex_yaml?
false
end
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) { |out|
out << "!ruby/module "
self.name.to_yaml( :Emitter => out )
}
end
end
YAML.add_ruby_type(/^module/) do |type, val|
subtype, subclass = YAML.read_type_class(type, Module)
val.split(/::/).inject(Object) { |p, n| p.const_get(n)}
end

class Class
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) { |out|
out << "!ruby/class "
self.name.to_yaml( :Emitter => out )
}
end
end
YAML.add_ruby_type(/^class/) do |type, val|
subtype, subclass = YAML.read_type_class(type, Class)
val.split(/::/).inject(Object) { |p, n| p.const_get(n)}
end

module M; class C; end; end

x = [String, Object, File, Process, Enumerable, M::C]

y x

p YAML.load(YAML.dump(x))

END

Output:


  • !ruby/class String
  • !ruby/class Object
  • !ruby/class File
  • !ruby/module Process
  • !ruby/module Enumerable
  • !ruby/class M::C
    [String, Object, File, Process, Enumerable, M::C]

Maybe the code should also check whether const_get returns the right
thing each time. Other than that, any pitfalls?