I need to create a class that prevents outside code from instantiating it directly. All instances are obtained by calling a couple of class methods, and also some instance methods that will generate new instances and return them.
class SomeClass
class << self
private :new, :allocate
end
def initialize(hash)
@hash = hash
end
# A class method that returns a new instance
def self.empty
new({}) # works fine!
end
# Another class method that returns a new instance
def self.double(a, b)
new({a => b}) # works fine!
end
# An instance method that will generate new instances
def combine_with(a, b)
# Here's the problem!
# Note: it doesn't work with self.class.new either
SomeClass.new(@hash.merge({a => b}))
end
end
So I defined the new method to be private. This works for the class methods, inside of them I can still call new internally. But I can’t call new from within the instance methods. I tried defining new as protected, but this didn’t help either.
did you try to use
send?