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 #9698] Fix an error for Style/StructInheritance #9699

Merged
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/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][])
10 changes: 9 additions & 1 deletion lib/rubocop/cop/style/struct_inheritance.rb
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/struct_inheritance_spec.rb
Expand Up @@ -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
Expand Down