Skip to content

Commit

Permalink
[Fix rubocop#8507] Fix Style/RescueModifier to handle parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmytro Savochkin committed Aug 16, 2020
1 parent e4cb8cd commit 3836c45
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down
38 changes: 29 additions & 9 deletions lib/rubocop/cop/style/rescue_modifier.rb
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/style/rescue_modifier_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit 3836c45

Please sign in to comment.