24

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 pass some parameters to #new when initializing that single instance? Example should always have certain properties initialized. For example, say I had a class whose sole purpose is to log to a file 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?

3
  • 2
    If you want to pass parameters in, are you sure you want to use a singleton? Mar 10, 2011 at 12:22
  • 4
    Yes. I believe there are situations in which a singleton makes sense but it's one that should have some initial configuration.
    – codecraig
    Mar 10, 2011 at 12:30
  • +1 because this is a good question. Singleton makes #new a private method, and even in Ruby 3.1.2 the documentation doesn't explain how to expose it without metaprogramming although there are some obscure methods that might serve. There are probably some cooler answers than the ones here (including mine) but it's a great question because it's challenging without being an unusual edge case. Aug 23, 2022 at 16:53

6 Answers 6

16

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  # => #<MyLogger:0x000.... @file_name="path/to/log/file">

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.

1
  • 4
    Why bothering to copy @@file_name into @file_name instead of just using @@file_name if it's a singleton anyway?
    – Gavriel
    Oct 28, 2015 at 10:12
4

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 do
      return @@singleton__instance__ if @@singleton__instance__

      @@singleton__instance__ = new(file_name)
    end
    @@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.

3
  • So I think I'd have to override self.new after creating the @@__singleton_instance__ otherwise you can still do MyLogger.new
    – codecraig
    Mar 10, 2011 at 12:51
  • Ok so here's what I came up with:
    – codecraig
    Mar 10, 2011 at 13:01
  • 1
    To stay more general set *params with the splat operator in method self.instance, like this (def self.instance *params), and set new calling, with a splat operator also new(*params).
    – rplaurindo
    Apr 24, 2016 at 7:11
3

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.

1

This was too long to put into a comment (e.g. stackoverflow said it was too long)

Ok so here's what I came up with:

class MyLogger
  @@singleton__instance__ = nil
  @@singleton__mutex__ = Mutex.new
  def self.config_instance file_name
    return @@singleton__instance__ if @@singleton__instance__
    @@singleton__mutex__.synchronize {
      return @@singleton__instance__ if @@singleton__instance__
      @@singleton__instance__ = new(file_name)
      def self.instance
        @@singleton__instance__
      end
      private_class_method :new
    }
    @@singleton__instance__
  end
  def self.instance
    raise "must call MyLogger.config_instance at least once"
  end
  private
  def initialize file_name
    @file_name = file_name
  end
end

This uses 'config_instance' to create and configure the singleton instance. It redefines the self.instance method once an instance is ready.

It also makes the 'new' class method private after creating the first instance.

1
  • fixed in my answer, you can set the privet new on class level, new will be still visible for def self.instance
    – mpapis
    Mar 10, 2011 at 13:18
1

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
# => #<MyLogger:0x007f8ec4833060 @filepath="some/default/path">

logger_b = MyLogger.instance
# => #<MyLogger:0x007f8ec4833060 @filepath="some/default/path">

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
0

Use Accessors

While I haven't found a really elegant solution for initializing a singleton the way you want, it's fairly trivial to implement this with an accessor. For example, in Ruby 3.1.2:

require 'singleton'

class Example
  include Singleton
  attr_accessor :file_name
end

#=> [:file_name, :file_name=]

You can then use the accessor to populate @file_name if it doesn't already contain a truthy value since instance variables auto-vivify as nil:

Example.instance.file_name ||= "/tmp/foo"
#=> "/tmp/foo"

Example.instance.file_name
#=> "/tmp/foo"

Example.instance
#=> #<Example:0x0000000108da72b8 @file_name="/tmp/foo">

Removing Writable Accessors After Setting a Value

Obviously, you can also re-assign the variable since you have a writable accessor. If you don't want to allow that on your singleton class after you've set your instance variable for the first time, just undefine the attr_writer method once it's truthy:

# @return [Class<Example>, nil] class if method removed; otherwise nil
Example.instance.singleton_class.undef_method(:file_name=) if
   Example.instance.file_name && Example.instance.respond_to?(:file_name=)

A Simplification with Caveats

You could do this all at once like so:

require 'singleton'

class Example
  include Singleton
  attr_accessor :file_name
end

Example.instance.file_name ||= "/tmp/foo"
Example.instance.singleton_class.undef_method(:file_name=)
Example.instance
#=> #<Example:0x0000000108da72b8 @file_name="/tmp/foo">

but if you don't know ahead of time whether your instance variable has been set you may prefer the more verbose approach. Your use cases may certainly vary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.