Skip to content

Commit

Permalink
[Fix #11663] Fix an incorrect autocorrect for Style/BlockDelimiters
Browse files Browse the repository at this point in the history
Fixes #11663.

This PR fixes an incorrect autocorrect for `Style/BlockDelimiters`
when multi-line blocks to `{` and `}` with arithmetic operation method chain.
  • Loading branch information
koic authored and bbatsov committed Mar 6, 2023
1 parent d8f6765 commit f982aa8
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11663](https://github.com/rubocop/rubocop/issues/11663): Fix an incorrect autocorrect for `Style/BlockDelimiters` when multi-line blocks to `{` and `}` with arithmetic operation method chain. ([@koic][])
9 changes: 9 additions & 0 deletions lib/rubocop/cop/style/block_delimiters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ def get_blocks(node, &block)
end

def proper_block_style?(node)
return true if require_braces?(node)
return special_method_proper_block_style?(node) if special_method?(node.method_name)

case style
Expand All @@ -352,6 +353,14 @@ def proper_block_style?(node)
end
end

def require_braces?(node)
return false unless node.braces?

node.each_ancestor(:send).any? do |send|
send.arithmetic_operation? && node.source_range.end_pos < send.loc.selector.begin_pos
end
end

def special_method?(method_name)
allowed_method?(method_name) ||
matches_allowed_pattern?(method_name) ||
Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/style/block_delimiters_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,26 @@
RUBY
end

it 'registers an offense and autocorrects when multi-line blocks to `{` and `}` with method chain' do
expect_offense(<<~RUBY)
foo bar + baz {
^ Avoid using `{...}` for multi-line blocks.
}.qux.quux
RUBY

expect_correction(<<~RUBY)
foo bar + baz do
end.qux.quux
RUBY
end

it 'does not register an offense when multi-line blocks to `{` and `}` with arithmetic operation method chain' do
expect_no_offenses(<<~RUBY)
foo bar + baz {
}.qux + quux
RUBY
end

it 'does not autocorrect {} if do-end would introduce a syntax error' do
expect_no_offenses(<<~RUBY)
my_method :arg1, arg2: proc {
Expand Down

0 comments on commit f982aa8

Please sign in to comment.