Skip to content

Commit

Permalink
Add ComparisonsThreshold config option to Style/MultipleComparison
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima authored and bbatsov committed May 13, 2023
1 parent 7c55b92 commit 37ee25f
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11873](https://github.com/rubocop/rubocop/pull/11873): Add `ComparisonsThreshold` config option to `Style/MultipleComparison`. ([@fatkodima][])
1 change: 1 addition & 0 deletions config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4383,6 +4383,7 @@ Style/MultipleComparison:
VersionAdded: '0.49'
VersionChanged: '1.1'
AllowMethodComparison: true
ComparisonsThreshold: 2

Style/MutableConstant:
Description: 'Do not assign mutable objects to constants.'
Expand Down
14 changes: 14 additions & 0 deletions lib/rubocop/cop/style/multiple_comparison.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ module Style
#
# # good
# foo if [b.lightweight, b.heavyweight].include?(a)
#
# @example ComparisonsThreshold: 2 (default)
# # bad
# foo if a == 'a' || a == 'b'
#
# @example ComparisonsThreshold: 3
# # good
# foo if a == 'a' || a == 'b'
#
class MultipleComparison < Base
extend AutoCorrector

Expand All @@ -58,6 +67,7 @@ def on_or(node)
return unless node == root_of_or_node
return unless nested_variable_comparison?(root_of_or_node)
return if @allowed_method_comparison
return if @compared_elements.size < comparisons_threshold

add_offense(node) do |corrector|
elements = @compared_elements.join(', ')
Expand Down Expand Up @@ -151,6 +161,10 @@ def reset_comparison
def allow_method_comparison?
cop_config.fetch('AllowMethodComparison', true)
end

def comparisons_threshold
cop_config.fetch('ComparisonsThreshold', 2)
end
end
end
end
Expand Down
28 changes: 28 additions & 0 deletions spec/rubocop/cop/style/multiple_comparison_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,32 @@ def do_something(foo, bar)
RUBY
end
end

context 'when `ComparisonsThreshold`: 2' do
let(:cop_config) { { 'ComparisonsThreshold' => 2 } }

it 'registers an offense and corrects when `a` is compared twice' do
expect_offense(<<~RUBY)
a = "a"
foo if a == "a" || a == "b"
^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY

expect_correction(<<~RUBY)
a = "a"
foo if ["a", "b"].include?(a)
RUBY
end
end

context 'when `ComparisonsThreshold`: 3' do
let(:cop_config) { { 'ComparisonsThreshold' => 3 } }

it 'does not register an offense when `a` is compared twice' do
expect_no_offenses(<<~RUBY)
a = "a"
foo if a == "a" || a == "b"
RUBY
end
end
end

0 comments on commit 37ee25f

Please sign in to comment.