Skip to content

Commit

Permalink
Revert "Simplify the implementation (#7)"
Browse files Browse the repository at this point in the history
This reverts commit 545b6b6.

  This change break Rails CI: https://bugs.ruby-lang.org/issues/19711
  • Loading branch information
hsbt committed Jun 5, 2023
1 parent 545b6b6 commit 911531d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
26 changes: 17 additions & 9 deletions lib/singleton.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def _dump(depth = -1)
module SingletonClassMethods # :nodoc:

def clone # :nodoc:
super.include(Singleton)
Singleton.__init__(super)
end

# By default calls instance(). Override to retain singleton state.
Expand All @@ -121,18 +121,31 @@ def _load(str)
end

def instance # :nodoc:
@singleton__instance__ || @singleton__mutex__.synchronize { @singleton__instance__ ||= new }
return @singleton__instance__ if @singleton__instance__
@singleton__mutex__.synchronize {
return @singleton__instance__ if @singleton__instance__
@singleton__instance__ = new()
}
@singleton__instance__
end

private

def inherited(sub_klass)
super
sub_klass.include(Singleton)
Singleton.__init__(sub_klass)
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
Expand All @@ -143,19 +156,14 @@ def append_features(mod)
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
klass.instance_eval {
@singleton__instance__ = nil
@singleton__mutex__ = Thread::Mutex.new
}
Singleton.__init__(klass)
end
end

Expand Down
11 changes: 0 additions & 11 deletions test/test_singleton.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,22 +94,11 @@ def test_inheritance_works_with_overridden_inherited_method
assert_same a, b
end

def test_inheritance_creates_separate_singleton
a = SingletonTest.instance
b = Class.new(SingletonTest).instance

assert_not_same a, b
end

def test_class_level_cloning_preserves_singleton_behavior
klass = SingletonTest.clone

a = klass.instance
b = klass.instance
assert_same a, b
end

def test_class_level_cloning_creates_separate_singleton
assert_not_same SingletonTest.instance, SingletonTest.clone.instance
end
end

0 comments on commit 911531d

Please sign in to comment.