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
>
Simple singleton that doesn't depend on Singleton
module
class MyLogger
def self.instance(filepath = File.join('some', 'default', 'path'))
@@instance ||= new(filepath).send(:configure)
end
def initialize(filepath)
@filepath = filepath
end
private_class_method :new
def info(msg)
puts msg
end
private
def configure
# do stuff
self
end
end
Example usage
logger_a = MyLogger.instance
# => #
logger_b = MyLogger.instance
# => #
logger_a.info logger_a.object_id
# 70125579507760
# => nil
logger_b.info logger_b.object_id
# 70125579507760
# => nil
logger_c = MyLogger.new('file/path')
# NoMethodError: private method `new' called for MyLogger:Class