I\'ve seen how to define a class as being a singleton (how to create a singleton in ruby):
require \'singleton\'
class Example
include Singleton
end
>
Here's another way to do it -- put the log file name in a class variable:
require 'singleton'
class MyLogger
include Singleton
@@file_name = ""
def self.file_name= fn
@@file_name = fn
end
def initialize
@file_name = @@file_name
end
end
Now you can use it this way:
MyLogger.file_name = "path/to/log/file"
log = MyLogger.instance # => #
Subsequent calls to instance
will return the same object with the path name unchanged, even if you later change the value of the class variable. A nice further touch would be to use another class variable to keep track of whether an instance has already been created, and have the file_name=
method raise an exception in that case. You could also have initialize
raise an exception if @@file_name
has not yet been set.