Skip to content

Commit

Permalink
Fix repeated conditional when local variables in diff methods
Browse files Browse the repository at this point in the history
  • Loading branch information
JuanVqz committed Oct 11, 2023
1 parent b1fa495 commit b50a544
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/reek/smell_detectors/repeated_conditional.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,18 @@ def max_identical_ifs
# @quality :reek:TooManyStatements { max_statements: 9 }
def conditional_counts
result = Hash.new { |hash, key| hash[key] = [] }
collector = proc do |node|
next unless (condition = node.condition)
next if condition == BLOCK_GIVEN_CONDITION
collector = proc do |method|
[:if, :case].map do |stmt|
method.each_node(stmt) do |node|
next unless (condition = node.condition)
next if condition == BLOCK_GIVEN_CONDITION

result[condition].push(condition.line)
result[method.name].push(condition.line)
end
end
end
[:if, :case].each { |stmt| context.local_nodes(stmt, &collector) }
context.local_nodes(:def, &collector)

result
end
end
Expand Down
23 changes: 23 additions & 0 deletions spec/reek/smell_detectors/repeated_conditional_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,27 @@ def echo

expect(src).to reek_of(:RepeatedConditional)
end

it 'does not report local repeated conditionals' do
src = <<-RUBY
class Alfa
def bravo
charlie = true
puts "Repeat 1!" if charlie
end
def delta
charlie = false
puts "Repeat 2!" if charlie
end
def echo
charlie = 123
puts "Repeat 3!" if charlie
end
end
RUBY

expect(src).not_to reek_of(:RepeatedConditional)
end
end

0 comments on commit b50a544

Please sign in to comment.