From ac73f3b6cdd6502462c7db6cd943f03541f42f1a Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 21 Jul 2022 12:01:48 +0900 Subject: [PATCH] [Fix #10825] Fix an incorrect autocorrect for `Style/ClassAndModuleChildren` Fixes #10825. This PR fixes an incorrect autocorrect for `Style/ClassAndModuleChildren` when using nested one-liner class. --- ...ocorrect_for_style_class_and_module_children.md | 1 + lib/rubocop/cop/style/class_and_module_children.rb | 8 ++++---- .../cop/style/class_and_module_children_spec.rb | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 changelog/fix_an_incorrect_autocorrect_for_style_class_and_module_children.md diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_class_and_module_children.md b/changelog/fix_an_incorrect_autocorrect_for_style_class_and_module_children.md new file mode 100644 index 00000000000..b07aeb44be7 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_class_and_module_children.md @@ -0,0 +1 @@ +* [#10825](https://github.com/rubocop/rubocop/issues/10825): Fix an incorrect autocorrect for `Style/ClassAndModuleChildren` when using nested one-liner class. ([@koic][]) diff --git a/lib/rubocop/cop/style/class_and_module_children.rb b/lib/rubocop/cop/style/class_and_module_children.rb index 334560337bb..7e0c157daa5 100644 --- a/lib/rubocop/cop/style/class_and_module_children.rb +++ b/lib/rubocop/cop/style/class_and_module_children.rb @@ -117,10 +117,10 @@ def compact_identifier_name(node) end def remove_end(corrector, body) - range = range_between( - body.loc.end.begin_pos - leading_spaces(body).size, - body.loc.end.end_pos + 1 - ) + remove_begin_pos = body.loc.end.begin_pos - leading_spaces(body).size + adjustment = processed_source.raw_source[remove_begin_pos] == ';' ? 0 : 1 + range = range_between(remove_begin_pos, body.loc.end.end_pos + adjustment) + corrector.remove(range) end 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 3f998f1aed6..68b6ecea935 100644 --- a/spec/rubocop/cop/style/class_and_module_children_spec.rb +++ b/spec/rubocop/cop/style/class_and_module_children_spec.rb @@ -367,6 +367,20 @@ class BazModule RUBY end + it 'registers a offense for classes with nested one-liner children' do + expect_offense(<<~RUBY) + class FooClass + ^^^^^^^^ Use compact module/class definition instead of nested style. + class BarClass; end + end + RUBY + + expect_correction(<<~RUBY) + class FooClass::BarClass + end + RUBY + end + it 'accepts class/module with single method' do expect_no_offenses(<<~RUBY) class FooClass