Skip to content

Commit e5ba696

Browse files
committed
Fix repeated conditional when local variables in diff methods
Fixes #1455
1 parent b1fa495 commit e5ba696

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

lib/reek/smell_detectors/repeated_conditional.rb

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,27 @@ def max_identical_ifs
7373
#
7474
# @quality :reek:TooManyStatements { max_statements: 9 }
7575
def conditional_counts
76-
result = Hash.new { |hash, key| hash[key] = [] }
77-
collector = proc do |node|
78-
next unless (condition = node.condition)
79-
next if condition == BLOCK_GIVEN_CONDITION
76+
result = {}
77+
collector = proc do |method|
78+
[:if, :case].map do |stmt|
79+
method.each_node(stmt) do |node|
80+
next unless (condition = node.condition)
81+
next if condition == BLOCK_GIVEN_CONDITION
8082

81-
result[condition].push(condition.line)
83+
if result.dig(condition).nil?
84+
result[condition] = {}
85+
end
86+
87+
if result.dig(condition, method.name).nil?
88+
result[condition][method.name] = [condition.line]
89+
else
90+
result[condition][method.name].push(condition.line)
91+
end
92+
end
93+
end
8294
end
83-
[:if, :case].each { |stmt| context.local_nodes(stmt, &collector) }
95+
context.local_nodes(:def, &collector)
96+
8497
result
8598
end
8699
end

spec/reek/smell_detectors/repeated_conditional_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,27 @@ def echo
9797

9898
expect(src).to reek_of(:RepeatedConditional)
9999
end
100+
101+
it 'does not report local repeated conditionals' do
102+
src = <<-RUBY
103+
class Alfa
104+
def bravo
105+
charlie = true
106+
puts "Repeat 1!" if charlie
107+
end
108+
109+
def delta
110+
charlie = false
111+
puts "Repeat 2!" if charlie
112+
end
113+
114+
def echo
115+
charlie = 123
116+
puts "Repeat 3!" if charlie
117+
end
118+
end
119+
RUBY
120+
121+
expect(src).not_to reek_of(:RepeatedConditional)
122+
end
100123
end

0 commit comments

Comments
 (0)