Reputation: 317
I have the code like below:
require 'logger'
require 'singleton'
class Logger
include Singleton
@@old_initialize = Logger.instance_method :initialize
def initialize
@@old_initialize.bind(self).call(STDERR)
end
end
class MyClass
def initialize
@logger = Logger.new("output.log")
end
end
I am getting following error while running MyClass.
in
initialize': private method
new' called for Logger:Class (NoMethodError)
I'm using Ruby Version:
ruby 1.8.6 (2009-08-04 patchlevel 383) [x86_64-linux]
Upvotes: 0
Views: 2533
Reputation: 29503
Let us look at the documentation of Module: Singleton. Including the module ensures, that only one instance of your class can be created by making the initialize
method private. Hence, you receive NoMethodError - new is private
error. Further it says:
The instance is created at upon the first call of
Klass.instance()
.
So instead of .new
you make a call to .instance
class MyClass
def initialize
@logger = Logger.instance()
end
end
Now you can call MyClass.new
and it will return your logger object. This way, however, you cannot pass an additional parameter. So the question here really is, why does it need to be a Singleton in the first place?
Upvotes: 3