Skip to content

Commit

Permalink
[Fix #9627] Fix an incorrect auto-correct for Style/StructInheritance
Browse files Browse the repository at this point in the history
Fixes #9627.

This PR fixes an incorrect auto-correct for `Style/StructInheritance` when
extending instance of Struct without `do` ... `end` and class body is empty.
  • Loading branch information
koic authored and bbatsov committed Mar 22, 2021
1 parent 1b910ce commit 0427ee4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
@@ -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][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/struct_inheritance.rb
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/struct_inheritance_spec.rb
Expand Up @@ -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)
Expand Down

0 comments on commit 0427ee4

Please sign in to comment.