Skip to content

Commit adeb5a8

Browse files
committed
Don't cache module_parent_name on anonymous modules
Fix: rails#53968 An anonymous module can become named if assigned later, hence it's incorrect to cache `module_parent_name` if the module is anonymous.
1 parent 3a91006 commit adeb5a8

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

activesupport/lib/active_support/core_ext/module/introspection.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ def module_parent_name
1010
if defined?(@parent_name)
1111
@parent_name
1212
else
13+
name = self.name
14+
return if name.nil?
15+
1316
parent_name = name =~ /::[^:]+\z/ ? -$` : nil
1417
@parent_name = parent_name unless frozen?
1518
parent_name

activesupport/test/core_ext/module/introspection_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ def test_module_parent_name_when_frozen
2626
assert_equal "ParentA::B", ParentA::B::FrozenC.module_parent_name
2727
end
2828

29+
def test_module_parent_name_notice_changes
30+
klass = Class.new
31+
assert_nil klass.module_parent_name
32+
ParentA.const_set(:NewClass, klass)
33+
assert_equal "ParentA", klass.module_parent_name
34+
ensure
35+
ParentA.send(:remove_const, :NewClass) if ParentA.const_defined?(:NewClass)
36+
end
37+
2938
def test_module_parent
3039
assert_equal ParentA::B, ParentA::B::C.module_parent
3140
assert_equal ParentA, ParentA::B.module_parent
@@ -36,4 +45,13 @@ def test_module_parents
3645
assert_equal [ParentA::B, ParentA, Object], ParentA::B::C.module_parents
3746
assert_equal [ParentA, Object], ParentA::B.module_parents
3847
end
48+
49+
def test_module_parent_notice_changes
50+
klass = Class.new
51+
assert_equal Object, klass.module_parent
52+
ParentA.const_set(:NewClass, klass)
53+
assert_equal ParentA, klass.module_parent
54+
ensure
55+
ParentA.send(:remove_const, :NewClass) if ParentA.const_defined?(:NewClass)
56+
end
3957
end

0 commit comments

Comments
 (0)