diff options
author | Daniel Pepper <[email protected]> | 2023-06-02 17:35:11 -0700 |
---|---|---|
committer | git <[email protected]> | 2023-06-03 00:35:18 +0000 |
commit | bebd05fb51ea65bc57344b67100748200f8311eb (patch) | |
tree | 371c2ab64251e480df6b6e7f5b03e2313c4de95c /lib/singleton.rb | |
parent | 4e26ae3cb93d6f22edef9d4fa1221e94b7abded2 (diff) |
[ruby/singleton] Simplify the implementation
(https://github.com/ruby/singleton/pull/7)
Remove `__init__` and move logic to `included`.
Diffstat (limited to 'lib/singleton.rb')
-rw-r--r-- | lib/singleton.rb | 26 |
1 files changed, 9 insertions, 17 deletions
diff --git a/lib/singleton.rb b/lib/singleton.rb index 07420d2ea2..757b77eba3 100644 --- a/lib/singleton.rb +++ b/lib/singleton.rb @@ -112,7 +112,7 @@ module Singleton module SingletonClassMethods # :nodoc: def clone # :nodoc: - Singleton.__init__(super) + super.include(Singleton) end # By default calls instance(). Override to retain singleton state. @@ -121,31 +121,18 @@ module Singleton end def instance # :nodoc: - return @singleton__instance__ if @singleton__instance__ - @singleton__mutex__.synchronize { - return @singleton__instance__ if @singleton__instance__ - @singleton__instance__ = new() - } - @singleton__instance__ + @singleton__instance__ || @singleton__mutex__.synchronize { @singleton__instance__ ||= new } end private def inherited(sub_klass) super - Singleton.__init__(sub_klass) + sub_klass.include(Singleton) end end class << Singleton # :nodoc: - def __init__(klass) # :nodoc: - klass.instance_eval { - @singleton__instance__ = nil - @singleton__mutex__ = Thread::Mutex.new - } - klass - end - private # extending an object with Singleton is a bad idea @@ -156,14 +143,19 @@ module Singleton unless mod.instance_of?(Class) raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}" end + super end def included(klass) super + klass.private_class_method :new, :allocate klass.extend SingletonClassMethods - Singleton.__init__(klass) + klass.instance_eval { + @singleton__instance__ = nil + @singleton__mutex__ = Thread::Mutex.new + } end end |