Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an incorrect auto-correct for Style/StructInheritance #8443

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -38,6 +38,7 @@
* [#8006](https://github.com/rubocop-hq/rubocop/issues/8006): Fix line length calculation for `Style/IfUnlessModifier` to correctly take into account code before the if condition when considering conversation to a single-line form. ([@dsavochkin][])
* [#8283](https://github.com/rubocop-hq/rubocop/issues/8283): Fix line length calculation for `Style/IfUnlessModifier` to correctly take into account a comment on the first line when considering conversation to a single-line form. ([@dsavochkin][])
* [#8226](https://github.com/rubocop-hq/rubocop/issues/8226): Fix `Style/IfUnlessModifier` to add parentheses when converting if-end condition inside an array or a hash to a single-line form. ([@dsavochkin][])
* [#8443](https://github.com/rubocop-hq/rubocop/pull/8443): Fix an incorrect auto-correct for `Style/StructInheritance` when there is a comment before class declaration. ([@koic][])

### Changes

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/struct_inheritance.rb
Expand Up @@ -33,7 +33,7 @@ def on_class(node)

def autocorrect(node)
lambda do |corrector|
corrector.remove(range_with_surrounding_space(range: node.loc.keyword))
corrector.remove(range_with_surrounding_space(range: node.loc.keyword, newlines: false))
corrector.replace(node.loc.operator, '=')

correct_parent(node.parent_class, corrector)
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/style/struct_inheritance_spec.rb
Expand Up @@ -60,6 +60,22 @@ class Person < ::Struct.new(:first_name, :last_name) do end
RUBY
end

it 'registers an offense when extending instance of `Struct` when there is a comment ' \
'before class declaration' do
expect_offense(<<~RUBY)
# comment
class Person < Struct.new(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
end
RUBY

expect_correction(<<~RUBY)
# comment
Person = Struct.new(:first_name, :last_name) do
end
RUBY
end

it 'accepts plain class' do
expect_no_offenses(<<~RUBY)
class Person
Expand Down