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 is an approach I used to solve a similar problem, which I wanted to share in case you or other people find it suitable:
require 'singleton'
class Logger
attr_reader :file_name
def initialize file_name
@file_name = file_name
end
end
class MyLogger < Logger
include Singleton
def self.new
super "path/to/file.log"
end
# You want to make {.new} private to maintain the {Singleton} approach;
# otherwise other instances of {MyLogger} can be easily constructed.
private_class_method :new
end
p MyLogger.instance.file_name
# => "path/to/file.log"
MyLogger.new "some/other/path"
# => ...private method `new' called for MyLogger:Class (NoMethodError)
I've tested the code in 2.3
, 2.4
and 2.5
; earlier versions may of course exhibit divergent behavior.
This allows you to have a general parametrized Logger
class, which can be used to create additional instances for testing or future alternative configurations, while defining MyLogger
as a single instance of it following to Ruby's standardized Singleton
pattern. You can split instance methods across them as you find appropriate.
Ruby's Singleton
constructs the instance automatically when first needed, so the Logger#initialize
parameters must be available on-demand in MyLogger.new
, but you can of course pull the values from the environment or set them up as MyLogger
class instance variables during configuration before the singleton instance is ever used, which is consistent with the singleton instance being effectively global.