Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a false positive for Style/RedundantReturn when a rescue has an else clause #8768

Merged
merged 1 commit into from Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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