Skip to content

Commit 911531d

Browse files
committed
Revert "Simplify the implementation (#7)"
This reverts commit 545b6b6. This change break Rails CI: https://bugs.ruby-lang.org/issues/19711
1 parent 545b6b6 commit 911531d

File tree

2 files changed

+17
-20
lines changed

2 files changed

+17
-20
lines changed

lib/singleton.rb

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def _dump(depth = -1)
112112
module SingletonClassMethods # :nodoc:
113113

114114
def clone # :nodoc:
115-
super.include(Singleton)
115+
Singleton.__init__(super)
116116
end
117117

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

123123
def instance # :nodoc:
124-
@singleton__instance__ || @singleton__mutex__.synchronize { @singleton__instance__ ||= new }
124+
return @singleton__instance__ if @singleton__instance__
125+
@singleton__mutex__.synchronize {
126+
return @singleton__instance__ if @singleton__instance__
127+
@singleton__instance__ = new()
128+
}
129+
@singleton__instance__
125130
end
126131

127132
private
128133

129134
def inherited(sub_klass)
130135
super
131-
sub_klass.include(Singleton)
136+
Singleton.__init__(sub_klass)
132137
end
133138
end
134139

135140
class << Singleton # :nodoc:
141+
def __init__(klass) # :nodoc:
142+
klass.instance_eval {
143+
@singleton__instance__ = nil
144+
@singleton__mutex__ = Thread::Mutex.new
145+
}
146+
klass
147+
end
148+
136149
private
137150

138151
# extending an object with Singleton is a bad idea
@@ -143,19 +156,14 @@ def append_features(mod)
143156
unless mod.instance_of?(Class)
144157
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
145158
end
146-
147159
super
148160
end
149161

150162
def included(klass)
151163
super
152-
153164
klass.private_class_method :new, :allocate
154165
klass.extend SingletonClassMethods
155-
klass.instance_eval {
156-
@singleton__instance__ = nil
157-
@singleton__mutex__ = Thread::Mutex.new
158-
}
166+
Singleton.__init__(klass)
159167
end
160168
end
161169

test/test_singleton.rb

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,22 +94,11 @@ def test_inheritance_works_with_overridden_inherited_method
9494
assert_same a, b
9595
end
9696

97-
def test_inheritance_creates_separate_singleton
98-
a = SingletonTest.instance
99-
b = Class.new(SingletonTest).instance
100-
101-
assert_not_same a, b
102-
end
103-
10497
def test_class_level_cloning_preserves_singleton_behavior
10598
klass = SingletonTest.clone
10699

107100
a = klass.instance
108101
b = klass.instance
109102
assert_same a, b
110103
end
111-
112-
def test_class_level_cloning_creates_separate_singleton
113-
assert_not_same SingletonTest.instance, SingletonTest.clone.instance
114-
end
115104
end

0 commit comments

Comments
 (0)