Skip to content

Commit

Permalink
[ruby/singleton] Simplify implementation of Singleton#instance.
Browse files Browse the repository at this point in the history
(ruby/singleton#9)

- Add more tests to cover rails' usage.
  • Loading branch information
dpep authored and matzbot committed Jun 5, 2023
1 parent 3fe0f8c commit 542c70a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
7 changes: 1 addition & 6 deletions lib/singleton.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,7 @@ def _load(str)
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
Expand Down
21 changes: 21 additions & 0 deletions test/test_singleton.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,32 @@ 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_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

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 542c70a

Please sign in to comment.