Skip to content

Commit

Permalink
[Fix rubocop#9698] Fix an error for Style/StructInheritance
Browse files Browse the repository at this point in the history
Fixes rubocop#9698.

This PR fixes an error for `Style/StructInheritance` when extending instance of
`Struct` without `do` ... `end` and class body is empty and single line definition.
  • Loading branch information
koic committed Apr 15, 2021
1 parent 26f3cc3 commit 0256efa
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
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

0 comments on commit 0256efa

Please sign in to comment.