# frozen_string_literal: false
# The Singleton module implements the Singleton pattern.
# To use Singleton, include the module in your class.
# This ensures that only one instance of Klass can be created.
# a,b = Klass.instance, Klass.instance
# # => NoMethodError - new is private ...
# The instance is created at upon the first call of Klass.instance().
# ObjectSpace.each_object(OtherKlass){}
# ObjectSpace.each_object(OtherKlass){}
# This behavior is preserved under inheritance and cloning.
# This above is achieved by:
# * Making Klass.new and Klass.allocate private.
# * Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the
# Singleton properties are kept when inherited and cloned.
# * Providing the Klass.instance() method that returns the same object each
# * Overriding Klass._load(str) to call Klass.instance().
# * Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent
# == Singleton and Marshal
# By default Singleton's #_dump(depth) returns the empty string. Marshalling by
# default will strip state information, e.g. instance variables and taint
# state, from the instance. Classes using Singleton can provide custom
# _load(str) and _dump(depth) methods to retain some of the previous state of
# attr_accessor :keep, :strip
# # this strips the @strip information from the instance
# Marshal.dump(@keep, depth)
# instance.keep = Marshal.load(str)
# a.strip = "get rid of this"
# stored_state = Marshal.dump(a)
# b = Marshal.load(stored_state)
# p a.keep # => "keep this"
# Raises a TypeError to prevent cloning.
raise TypeError, "can't clone instance of singleton #{self.class}"
# Raises a TypeError to prevent duping.
raise TypeError, "can't dup instance of singleton #{self.class}"
# By default, do not retain any state when marshalling.
module SingletonClassMethods # :nodoc:
Singleton.__init__(super)
# By default calls instance(). Override to retain singleton state.
Singleton.__init__(sub_klass)
class << Singleton # :nodoc:
def __init__(klass) # :nodoc:
@singleton__instance__ = nil
@singleton__mutex__ = Thread::Mutex.new
def klass.instance # :nodoc:
return @singleton__instance__ if @singleton__instance__
@singleton__mutex__.synchronize {
return @singleton__instance__ if @singleton__instance__
@singleton__instance__ = new()
# extending an object with Singleton is a bad idea
undef_method :extend_object
# help out people counting on transitive mixins
unless mod.instance_of?(Class)
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
klass.private_class_method :new, :allocate
klass.extend SingletonClassMethods
Singleton.__init__(klass)
# :singleton-method: _load
# By default calls instance(). Override to retain singleton state.