> > I don't yet fully understand your code
I am posting the solution I came up with, seeking critical commentary.
In particular I am unsure whether my use of YAML's "add_domain_type"
(where I've got a separate entry for each constant X for which
"X.yamlize_as_constant" is called) is in the spirit of how YAML was
designed to be used.
Any comments appreciated.
--Brian Buckley
module YamlizeAsConstant
def yamlize_as_constant(name = nil, domain = "aw.com,2005")
name = (self.class.name + "/" + constant_name).downcase if !name
yaml_name = "!" + domain + "/" + name
(class << self; self; end).class_eval do
define_method("to_yaml_type") {|*args| yaml_name}
define_method("to_yaml_properties"){|*args| []} #no
properties saved
end
#don't make an new object, rather return the constant
YAML.add_domain_type(domain, name) {|type, val| self}
end
def constant_name
self.class.constants.each do |c|
return c if self.class.const_get(c) == self
end
nil
end
end
class Object
include YamlizeAsConstant
end
class Foo
attr_accessor :a, :b # many more
FOO1 = Foo.new
FOO1.a = "test text a"
FOO1.b = "test text b"
FOO1.yamlize_as_constant
end
class TestYamlizeAsConstant < Test::Unit::TestCase
def test_foo
assert_equal "--- !aw.com,2005/foo/foo1 {}", Foo::FOO1.to_yaml
assert_same Foo::FOO1, YAML::load(Foo::FOO1.to_yaml)
end
end