Skip to content

Commit

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

This PR fixes an incorrect auto-correct for `Style/BlockDelimiters`
when there is a comment after the closing brace and using method chain.
  • Loading branch information
koic authored and bbatsov committed Aug 24, 2021
1 parent b00265b commit 5574410
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
@@ -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

0 comments on commit 5574410

Please sign in to comment.