diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_struct_inheritance.md b/changelog/fix_an_incorrect_autocorrect_for_style_struct_inheritance.md new file mode 100644 index 00000000000..f9dddf4d59b --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_struct_inheritance.md @@ -0,0 +1 @@ +* [#9627](https://github.com/rubocop/rubocop/issues/9627): Fix an incorrect auto-correct for `Style/StructInheritance` when extending instance of Struct without `do` ... `end` and class body is empty. ([@koic][]) diff --git a/lib/rubocop/cop/style/struct_inheritance.rb b/lib/rubocop/cop/style/struct_inheritance.rb index 47af290510e..8250e5ea3ec 100644 --- a/lib/rubocop/cop/style/struct_inheritance.rb +++ b/lib/rubocop/cop/style/struct_inheritance.rb @@ -48,6 +48,8 @@ def on_class(node) def correct_parent(parent, corrector) if parent.block_type? corrector.remove(range_with_surrounding_space(range: parent.loc.end, newlines: false)) + elsif (class_node = parent.parent).body.nil? + corrector.remove(range_by_whole_lines(class_node.loc.end, include_final_newline: true)) else corrector.insert_after(parent.loc.expression, ' do') end diff --git a/spec/rubocop/cop/style/struct_inheritance_spec.rb b/spec/rubocop/cop/style/struct_inheritance_spec.rb index b2cbc2c0a59..55c52fc2358 100644 --- a/spec/rubocop/cop/style/struct_inheritance_spec.rb +++ b/spec/rubocop/cop/style/struct_inheritance_spec.rb @@ -44,6 +44,18 @@ class Person < Struct.new(:first_name, :last_name) do end RUBY end + it 'registers an offense when extending instance of Struct without `do` ... `end` and class body is empty' do + expect_offense(<<~RUBY) + class Person < Struct.new(:first_name, :last_name) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct. + end + RUBY + + expect_correction(<<~RUBY) + Person = Struct.new(:first_name, :last_name) + RUBY + end + it 'registers an offense when extending instance of ::Struct with ' \ 'do ... end' do expect_offense(<<~RUBY)