I am fighting with singleton patterns in Ruby.
I know that singleton implements a single instance of an object but I don't quite understand if we can replicate it without the singleton module.
Then there is the issue with private methods; Right now I have to do something like this:
class MyTestClass
private_class_method :new
class << self
def test
puts hello
end
private
def hello
'hello world'
end
end
end
MyTestClass.test
So my questions are:
1 . Is the above a good Singleton pattern
Probably not. Using only class methods you don't get the benefit of having an initialize
function executed for your single "instance", so it is missing some pieces you would normally find in a Singleton. Ruby is flexible enough so you can bolt on any missing features to the "class" object as needed, but it starts to look kind of ugly.
2 . Would this make sure there is only a single instance?
Yes. You are modifying the object which represents the class, and there is only one.
3 . Is there a way to have private methods using the singleton module?
Yes. Have you tried? Its just as you would expect.
class Test
include Singleton
def public_test
"foo"
end
private
def private_test
"bar"
end
end
Test.instance.public_test # => "foo"
Test.instance.private_test # => throws exception
Test.instance.send(:private_test) # => "bar"