I have a class whose new method has been made private because I want only my class method “constructors” to create new instances. However, I also now need to have some instance methods create new instances too.
For example, look at the following snippet. It is in method_a where I’m having trouble:
Class Foo
class << self
#a "constructor" method
def from_x arg
stuff_from_arg = arg.something #something meaningful from arg
new(stuff_from_arg)
end
end
def initialize stuff
@stuff = stuff
end
private_class_method :new #forces use of Foo.from_x
def method_a
other_stuff = "blah"
#These do not work
return new(blah) #nope, instance cannot see class method
return self.class.new(blah) #nope, new is private_class_method
return Foo.new(blah) #same as previous line
return initialize(blah) #See *, but still doesn't work as expected
end
end
What I’m starting to think is that I may have designed this class in such a way that I need to make another class constructor method to create a new Foo, like this:
#in addition to previous code
Class Foo
class << self
def just_like_new stuff
new(stuff)
end
end
end
This doesn’t feel very right or very DRY, but perhaps this is the bed I’ve made for myself. Is there anything I can do?
*This line has been a bit surprising. It returns blah. Outside of a class definition, there is also an initialize and it takes 0 arguments and returns nil Does anyone know what is happening here?
You can always use
sendto get around the access control: