Skip to content

Commit

Permalink
Merge pull request #8768 from fatkodima/redundant_return-rescue-else
Browse files Browse the repository at this point in the history
Fix a false positive for `Style/RedundantReturn` when a rescue has an else clause
  • Loading branch information
koic committed Sep 22, 2020
2 parents e18f297 + cadc82a commit c70badc
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#8720](https://github.com/rubocop-hq/rubocop/issues/8720): Fix an error for `Lint/IdentityComparison` when calling `object_id` method without receiver in LHS or RHS. ([@koic][])
* [#8767](https://github.com/rubocop-hq/rubocop/issues/8767): Fix a false positive for `Style/RedundantReturn` when a rescue has an else clause. ([@fatkodima][])
* [#8710](https://github.com/rubocop-hq/rubocop/issues/8710): Fix a false positive for `Layout/RescueEnsureAlignment` when `Layout/BeginEndAlignment` cop is not enabled status. ([@koic][])
* [#8726](https://github.com/rubocop-hq/rubocop/issues/8726): Fix a false positive for `Naming/VariableNumber` when naming multibyte character variable name. ([@koic][])
* [#8730](https://github.com/rubocop-hq/rubocop/issues/8730): Fix an error for `Lint/UselessTimes` when there is a blank line in the method definition. ([@koic][])
Expand Down
13 changes: 8 additions & 5 deletions lib/rubocop/cop/style/redundant_return.rb
Expand Up @@ -108,8 +108,8 @@ def check_branch(node)
when :return then check_return_node(node)
when :case then check_case_node(node)
when :if then check_if_node(node)
when :rescue, :resbody
check_rescue_node(node)
when :rescue then check_rescue_node(node)
when :resbody then check_resbody_node(node)
when :ensure then check_ensure_node(node)
when :begin, :kwbegin
check_begin_node(node)
Expand Down Expand Up @@ -137,9 +137,12 @@ def check_if_node(node)
end

def check_rescue_node(node)
node.child_nodes.each do |child_node|
check_branch(child_node)
end
node.branches.each { |branch| check_branch(branch) }
check_branch(node.body) unless node.else?
end

def check_resbody_node(node)
check_branch(node.body)
end

def check_ensure_node(node)
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/redundant_return_spec.rb
Expand Up @@ -344,6 +344,27 @@ def func
end
RUBY
end

it 'registers an offense and corrects when rescue has else clause' do
expect_offense(<<~RUBY)
def func
return 3
rescue SomeException
else
return 4
^^^^^^ Redundant `return` detected.
end
RUBY

expect_correction(<<~RUBY)
def func
return 3
rescue SomeException
else
4
end
RUBY
end
end

context 'when return is inside an if-branch' do
Expand Down

0 comments on commit c70badc

Please sign in to comment.