I’m aware of the case where you have a few constructors, but they are
implemented as some kind of “syntax sugar” on top of one constructor
that does all the work (the example from “Singletons and other
Constructors” in Pickaxe chapter 3).
I have two different ways of creating an object, and I can’t write
them all in terms of one single constructor. Also, I can’t write
them in terms of public methods of the object (they set up internal
things that can’t be changed by the public).
I thought I could do this:
class Foo
private_class_method :new
private :create
private :decode
def Foo.create(*args)
new.create(*args)
end
def Foo.decode(*args)
new.decode(*args)
end
def create(a, b)
puts "create(#{a},#{b})"
self
end
def decode(a)
puts "decode(#{a})"
self
end
end
Foo.create(1,2)
Foo.decode(3)
Foo.decode(4).decode(5) # Should NOT work!
But I’m not happy with it. I don’t want it to be possible for the
constructor methods to be called on an object by anything other than
the Foo.*() constructors, but I can’t limit the access to only methods
of Foo.
This is starting to feel ridiculously hard, I must be missing something,
how is this supposed to be done?
Sam