Here’s a thought question for you. If you read the subject line, you
already know the answer.
A user-defined class has an initializer. When/how would you ever create
an instance of that class without calling the initializer?
Hmm.
The answer, of course, is when you load it from a marshaled format such
as YAML.
This brings me to my question.
When entities have default values in the constructor, we can omit them
when calling #new.
I’d like to be able to omit these in YAML also. (I can omit them now,
of course, but they get nil values).
Here’s some code in case it clarifies a little.
require “yaml”
class MyClass
def initialize(a,b,c=5)
@alpha, @beta, @gamma = a,b,c
end
end
foo = MyClass.new(3,4)
y1 = foo.to_yaml
y2 = y1.split("\n").find_all {|x| x !~ /gamma/ }.join("\n")
y2 has no gamma
f2 = YAML.load(y2)
p f2
I’d like f2 to have a ‘5’ for @gamma
Is this doable with add_domain_type or something? This is beyond my
current knowledge of YAML.
A part of me wishes that YAML could somehow be smart enough to call
the constructor, maybe with a special call like ‘construct’ instead
of ‘load’ – but there are likely ramifications I haven’t thought of.
Thanks,
Hal