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 #10033] Fix an incorrect auto-correct for Style/BlockDelimiters #10035

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
@@ -0,0 +1 @@
* [#10033](https://github.com/rubocop/rubocop/issues/10033): Fix an incorrect auto-correct for `Style/BlockDelimiters` when there is a comment after the closing brace and using method chanin. ([@koic][])
16 changes: 12 additions & 4 deletions lib/rubocop/cop/style/block_delimiters.rb
@@ -1,5 +1,6 @@
# frozen_string_literal: true

# rubocop:disable Metrics/ClassLength
module RuboCop
module Cop
module Style
Expand Down Expand Up @@ -275,14 +276,20 @@ def whitespace_after?(range, length = 1)
end

def move_comment_before_block(corrector, comment, block_node, closing_brace)
range = range_between(closing_brace.end_pos, comment.loc.expression.end_pos)

corrector.remove(range_with_surrounding_space(range: range, side: :right))
corrector.insert_after(closing_brace, "\n")
range = block_node.chained? ? end_of_chain(block_node.parent).source_range : closing_brace
comment_range = range_between(range.end_pos, comment.loc.expression.end_pos)
corrector.remove(range_with_surrounding_space(range: comment_range, side: :right))
corrector.insert_after(range, "\n")

corrector.insert_before(block_node, "#{comment.text}\n")
end

def end_of_chain(node)
return node unless node.chained?

end_of_chain(node.parent)
end

def get_blocks(node, &block)
case node.type
when :block
Expand Down Expand Up @@ -411,3 +418,4 @@ def array_or_range?(node)
end
end
end
# rubocop:enable Metrics/ClassLength
14 changes: 14 additions & 0 deletions spec/rubocop/cop/style/block_delimiters_spec.rb
Expand Up @@ -368,6 +368,20 @@
RUBY
end

it 'registers an offense when there is a comment after the closing brace and using method chain' do
expect_offense(<<~RUBY)
baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
foo(x) }.qux.quux # comment
RUBY

expect_correction(<<~RUBY)
# comment
baz.map do |x|
foo(x) end.qux.quux
RUBY
end

it 'registers an offense when there is a comment after the closing brace and block body is empty' do
expect_offense(<<~RUBY)
baz.map { |x|
Expand Down