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 #9588] Fix causing a variable to be shadowed from outside the rescue block #9961

Merged
merged 1 commit into from Sep 28, 2021
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/fix_causing_a_variable_to_be_shadowed.md
@@ -0,0 +1 @@
* [#9588](https://github.com/rubocop/rubocop/issues/9588): Fix causing a variable to be shadowed from outside the rescue block in the logic of Naming/RescuedExceptionsVariableName. ([@lilisako][])
7 changes: 7 additions & 0 deletions lib/rubocop/cop/naming/rescued_exceptions_variable_name.rb
Expand Up @@ -75,6 +75,9 @@ def on_resbody(node)
preferred_name = preferred_name(offending_name)
return if preferred_name.to_sym == offending_name

# check variable shadowing for exception variable
return if shadowed_variable_name?(node)

range = offense_range(node)
message = message(node)

Expand Down Expand Up @@ -150,6 +153,10 @@ def message(node)
preferred_name = preferred_name(offending_name)
format(MSG, preferred: preferred_name, bad: offending_name)
end

def shadowed_variable_name?(node)
node.each_descendant(:lvar).any? { |n| n.children.first.to_s == preferred_name(n) }
end
end
end
end
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/naming/rescued_exceptions_variable_name_spec.rb
Expand Up @@ -130,6 +130,19 @@
end
end

context 'shadowing an external variable' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
e = 'error message'
begin
something
rescue StandardError => e1
log(e, e1)
end
RUBY
end
end

context 'with lower letters class name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
Expand Down