diff --git a/changelog/fix_an_error_for_style_struct_inheritance.md b/changelog/fix_an_error_for_style_struct_inheritance.md new file mode 100644 index 00000000000..3a6e29ad4b7 --- /dev/null +++ b/changelog/fix_an_error_for_style_struct_inheritance.md @@ -0,0 +1 @@ +* [#9698](https://github.com/rubocop/rubocop/issues/9698): Fix an error for `Style/StructInheritance` when extending instance of `Struct` without `do` ... `end` and class body is empty and single line definition. ([@koic][]) diff --git a/lib/rubocop/cop/style/struct_inheritance.rb b/lib/rubocop/cop/style/struct_inheritance.rb index 8250e5ea3ec..a367e06c688 100644 --- a/lib/rubocop/cop/style/struct_inheritance.rb +++ b/lib/rubocop/cop/style/struct_inheritance.rb @@ -49,11 +49,19 @@ 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)) + corrector.remove(range_for_empty_class_body(class_node, parent)) else corrector.insert_after(parent.loc.expression, ' do') end end + + def range_for_empty_class_body(class_node, struct_new) + if class_node.single_line? + range_between(struct_new.source_range.end_pos, class_node.source_range.end_pos) + else + range_by_whole_lines(class_node.loc.end, include_final_newline: true) + end + end end end end diff --git a/spec/rubocop/cop/style/struct_inheritance_spec.rb b/spec/rubocop/cop/style/struct_inheritance_spec.rb index fb39eda4acc..e8afa10e912 100644 --- a/spec/rubocop/cop/style/struct_inheritance_spec.rb +++ b/spec/rubocop/cop/style/struct_inheritance_spec.rb @@ -56,6 +56,17 @@ class Person < Struct.new(:first_name, :last_name) RUBY end + it 'registers an offense when extending instance of Struct without `do` ... `end` and class body is empty and single line definition' do + expect_offense(<<~RUBY) + class Person < Struct.new(:first_name, :last_name); end + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct. + 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) class Person < ::Struct.new(:first_name, :last_name) do end