diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_block_delimiters.md b/changelog/fix_an_incorrect_autocorrect_for_style_block_delimiters.md new file mode 100644 index 00000000000..2cee0a83da6 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_block_delimiters.md @@ -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][]) diff --git a/lib/rubocop/cop/style/block_delimiters.rb b/lib/rubocop/cop/style/block_delimiters.rb index c0ec43781e0..19ec746eefb 100644 --- a/lib/rubocop/cop/style/block_delimiters.rb +++ b/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 @@ -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 @@ -411,3 +418,4 @@ def array_or_range?(node) end end end +# rubocop:enable Metrics/ClassLength diff --git a/spec/rubocop/cop/style/block_delimiters_spec.rb b/spec/rubocop/cop/style/block_delimiters_spec.rb index 51b9efe5281..fe3ef69e4a0 100644 --- a/spec/rubocop/cop/style/block_delimiters_spec.rb +++ b/spec/rubocop/cop/style/block_delimiters_spec.rb @@ -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|