Skip to content

Commit 545b6b6

Browse files
authored
Simplify the implementation (#7)
Remove `__init__` and move logic to `included`.
1 parent d1bfcba commit 545b6b6

File tree

2 files changed

+20
-17
lines changed

2 files changed

+20
-17
lines changed

lib/singleton.rb

Lines changed: 9 additions & 17 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-
Singleton.__init__(super)
115+
super.include(Singleton)
116116
end
117117

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

123123
def instance # :nodoc:
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__
124+
@singleton__instance__ || @singleton__mutex__.synchronize { @singleton__instance__ ||= new }
130125
end
131126

132127
private
133128

134129
def inherited(sub_klass)
135130
super
136-
Singleton.__init__(sub_klass)
131+
sub_klass.include(Singleton)
137132
end
138133
end
139134

140135
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-
149136
private
150137

151138
# extending an object with Singleton is a bad idea
@@ -156,14 +143,19 @@ def append_features(mod)
156143
unless mod.instance_of?(Class)
157144
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
158145
end
146+
159147
super
160148
end
161149

162150
def included(klass)
163151
super
152+
164153
klass.private_class_method :new, :allocate
165154
klass.extend SingletonClassMethods
166-
Singleton.__init__(klass)
155+
klass.instance_eval {
156+
@singleton__instance__ = nil
157+
@singleton__mutex__ = Thread::Mutex.new
158+
}
167159
end
168160
end
169161

test/test_singleton.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,22 @@ 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+
97104
def test_class_level_cloning_preserves_singleton_behavior
98105
klass = SingletonTest.clone
99106

100107
a = klass.instance
101108
b = klass.instance
102109
assert_same a, b
103110
end
111+
112+
def test_class_level_cloning_creates_separate_singleton
113+
assert_not_same SingletonTest.instance, SingletonTest.clone.instance
114+
end
104115
end

0 commit comments

Comments
 (0)