[ruby/singleton] Simplify implementation of `Singleton#instance`.

(https://github.com/ruby/singleton/pull/9)

- Add more tests to cover rails' usage.
This commit is contained in:
Daniel Pepper 2023-06-04 21:29:32 -07:00 коммит произвёл git
Родитель 3fe0f8c68b
Коммит 542c70aab7
2 изменённых файлов: 22 добавлений и 6 удалений

Просмотреть файл

@ -121,12 +121,7 @@ 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

Просмотреть файл

@ -94,6 +94,23 @@ class TestSingleton < Test::Unit::TestCase
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_inheritance_instantiation
klass = Class.new do
include Singleton
public_class_method :new
end
assert Class.new(klass).new
end
def test_class_level_cloning_preserves_singleton_behavior
klass = SingletonTest.clone
@ -101,4 +118,8 @@ class TestSingleton < Test::Unit::TestCase
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