diff --git a/changelog/fix_clobbering_error_in_class_and_module_children_cop.md b/changelog/fix_clobbering_error_in_class_and_module_children_cop.md new file mode 100644 index 00000000000..24fc125c52b --- /dev/null +++ b/changelog/fix_clobbering_error_in_class_and_module_children_cop.md @@ -0,0 +1 @@ +* [#9766](https://github.com/rubocop/rubocop/pull/9766): Fix a clobbering error for `Style/ClassAndModuleChildren` cop with compact style. ([@tejasbubane][]) diff --git a/lib/rubocop/cop/style/class_and_module_children.rb b/lib/rubocop/cop/style/class_and_module_children.rb index 1a03cf43478..d32803f647f 100644 --- a/lib/rubocop/cop/style/class_and_module_children.rb +++ b/lib/rubocop/cop/style/class_and_module_children.rb @@ -132,6 +132,9 @@ def check_nested_style(node) end def check_compact_style(node, body) + parent = node.parent + return if parent&.class_type? || parent&.module_type? + return unless needs_compacting?(body) add_offense(node.loc.name, message: COMPACT_MSG) do |corrector| diff --git a/spec/rubocop/cop/style/class_and_module_children_spec.rb b/spec/rubocop/cop/style/class_and_module_children_spec.rb index f3b1312ad3a..fb9800b3faf 100644 --- a/spec/rubocop/cop/style/class_and_module_children_spec.rb +++ b/spec/rubocop/cop/style/class_and_module_children_spec.rb @@ -227,6 +227,23 @@ class Foo::Bar::Baz RUBY end + it 'registers and offense for deeply nested children' do + expect_offense(<<~RUBY) + class Foo + ^^^ Use compact module/class definition instead of nested style. + class Bar + class Baz + end + end + end + RUBY + + expect_correction(<<~RUBY) + class Foo::Bar::Baz + end + RUBY + end + it 'registers an offense for modules with partially nested children' do expect_offense(<<~RUBY) module Foo::Bar