Skip to content

Commit

Permalink
[Fix rubocop#9599] Fix an error for Style/CaseLikeIf
Browse files Browse the repository at this point in the history
Fixes rubocop#9599.

This PR fixes an error for `Style/CaseLikeIf`
when using `include?` without a receiver.
  • Loading branch information
koic committed Mar 16, 2021
1 parent 972656f commit 62d0620
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_error_for_style_case_like_if.md
@@ -0,0 +1 @@
* [#9599](https://github.com/rubocop/rubocop/issues/9599): Fix an error for `Style/CaseLikeIf` when using `include?` without a receiver. ([@koic][])
19 changes: 15 additions & 4 deletions lib/rubocop/cop/style/case_like_if.rb
Expand Up @@ -105,8 +105,7 @@ def find_target_in_send_node(node)
when :===
node.arguments.first
when :include?, :cover?
receiver = deparenthesize(node.receiver)
node.arguments.first if receiver.range_type?
find_target_in_include_or_cover_node(node)
when :match, :match?, :=~
find_target_in_match_node(node)
end
Expand All @@ -124,6 +123,12 @@ def find_target_in_equality_node(node)
end
end

def find_target_in_include_or_cover_node(node)
return unless (receiver = node.receiver)

node.first_argument if deparenthesize(receiver).range_type?
end

def find_target_in_match_node(node)
argument = node.arguments.first
receiver = node.receiver
Expand Down Expand Up @@ -167,8 +172,7 @@ def condition_from_send_node(node, target)
lhs, _method, rhs = *node
lhs if rhs == target
when :include?, :cover?
receiver = deparenthesize(node.receiver)
receiver if receiver.range_type? && node.arguments.first == target
condition_from_include_or_cover_node(node, target)
end
end
# rubocop:enable Metrics/CyclomaticComplexity
Expand All @@ -184,6 +188,13 @@ def condition_from_match_node(node, target)
condition_from_binary_op(lhs, rhs, target)
end

def condition_from_include_or_cover_node(node, target)
return unless (receiver = node.receiver)

receiver = deparenthesize(receiver)
receiver if receiver.range_type? && node.first_argument == target
end

def condition_from_binary_op(lhs, rhs, target)
lhs = deparenthesize(lhs)
rhs = deparenthesize(rhs)
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/style/case_like_if_spec.rb
Expand Up @@ -156,6 +156,24 @@
RUBY
end

it 'does not register an offense when using `include?` without a receiver' do
expect_no_offenses(<<~RUBY)
if include?(Foo)
elsif include?(Bar)
else
end
RUBY
end

it 'does not register an offense when using `cover?` without a receiver' do
expect_no_offenses(<<~RUBY)
if x == 1
elsif cover?(Bar)
else
end
RUBY
end

it 'registers an offense and corrects when using `=~`' do
expect_offense(<<~RUBY)
if /foo/ =~ x
Expand Down

0 comments on commit 62d0620

Please sign in to comment.