Skip to content

Commit

Permalink
Merge pull request #9961 from lilisako/fix-shadow-variable-in-rescued…
Browse files Browse the repository at this point in the history
…-exceptions-variable-name

[Fix #9588] Fix causing a variable to be shadowed from outside the rescue block
  • Loading branch information
koic committed Sep 28, 2021
2 parents 6ae8d95 + ada5ffa commit a94b9fa
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
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

0 comments on commit a94b9fa

Please sign in to comment.