codecraig codecraig - 4 months ago 15
Ruby Question

ruby - create singleton with parameters?

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


But what if I want to give it some parameters for that single instance, meaning, the Example should always have certain properties initialized. For example, say I had a class whose sole purpose is to log to a file (this is just an example) but it requires a name of a file to log to before it can work.

class MyLogger
def initialize(file_name)
@file_name = file_name
end
end


How can I make MyLogger a singleton but make sure it gets a file_name?

Answer

Singleton does not provide this functionality, but instead of using singleton you could write it by yourself

class MyLogger
  @@singleton__instance__ = nil
  @@singleton__mutex__ = Mutex.new
  def self.instance file_name
    return @@singleton__instance__ if @@singleton__instance__
    @@singleton__mutex__.synchronize {
      return @@singleton__instance__ if @@singleton__instance__
      @@singleton__instance__ = new(file_name)
    }
    @@singleton__instance__
  end
  private
  def initialize file_name
    @file_name = file_name
  end
  private_class_method :new
end

It should work, but I did not tested the code.

This code forces you to use MyLogger.instance <file_name> or at least at the first call if you know it will be first time calling.