diff --git a/CHANGELOG.md b/CHANGELOG.md index c113923123f..af71e100979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#8508](https://github.com/rubocop-hq/rubocop/pull/8508): Fix a false positive for `Style/CaseLikeIf` when conditional contains comparison with a class. Mark `Style/CaseLikeIf` as not safe. ([@fatkodima][]) * [#8534](https://github.com/rubocop-hq/rubocop/issues/8534): Fix `Lint/BinaryOperatorWithIdenticalOperands` for binary operators used as unary operators. ([@marcandre][]) * [#8537](https://github.com/rubocop-hq/rubocop/pull/8537): Allow a trailing comment as a description comment for `Bundler/GemComment`. ([@pocke][]) +* [#8507](https://github.com/rubocop-hq/rubocop/issues/8507): Fix `Style/RescueModifier` to handle parentheses around rescue modifiers. ([@dsavochkin][]) ### Changes diff --git a/lib/rubocop/cop/style/rescue_modifier.rb b/lib/rubocop/cop/style/rescue_modifier.rb index a6683b9073a..884934906a9 100644 --- a/lib/rubocop/cop/style/rescue_modifier.rb +++ b/lib/rubocop/cop/style/rescue_modifier.rb @@ -52,20 +52,40 @@ def on_resbody(node) end def autocorrect(node) + parenthesized = parenthesized?(node) + lambda do |corrector| + corrector.replace(node, corrected_block(node, parenthesized)) + ParenthesesCorrector.correct(corrector, node.parent) if parenthesized + end + end + + private + + def parenthesized?(node) + node.parent && parentheses?(node.parent) + end + + def corrected_block(node, parenthesized) operation, rescue_modifier, = *node *_, rescue_args = *rescue_modifier - indent = indentation(node) - correction = - "begin\n" \ - "#{operation.source.gsub(/^/, indent)}" \ - "\n#{offset(node)}rescue\n" \ - "#{rescue_args.source.gsub(/^/, indent)}" \ - "\n#{offset(node)}end" + node_indentation, node_offset = indentation_and_offset(node, parenthesized) - lambda do |corrector| - corrector.replace(node, correction) + "begin\n" \ + "#{operation.source.gsub(/^/, node_indentation)}" \ + "\n#{node_offset}rescue\n" \ + "#{rescue_args.source.gsub(/^/, node_indentation)}" \ + "\n#{node_offset}end" + end + + def indentation_and_offset(node, parenthesized) + node_indentation = indentation(node) + node_offset = offset(node) + if parenthesized + node_indentation = node_indentation[0...-1] + node_offset = node_offset[0...-1] end + [node_indentation, node_offset] end end end diff --git a/spec/rubocop/cop/style/rescue_modifier_spec.rb b/spec/rubocop/cop/style/rescue_modifier_spec.rb index 18688da66b8..11843531fcf 100644 --- a/spec/rubocop/cop/style/rescue_modifier_spec.rb +++ b/spec/rubocop/cop/style/rescue_modifier_spec.rb @@ -80,6 +80,21 @@ def a_method RUBY end + it 'handles parentheses around a rescue modifier' do + expect_offense(<<~RUBY) + (foo rescue nil) + ^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. + RUBY + + expect_correction(<<~RUBY) + begin + foo + rescue + nil + end + RUBY + end + it 'does not register an offense for normal rescue' do expect_no_offenses(<<~RUBY) begin