Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #9599] Fix an error for Style/CaseLikeIf #9600

Merged
merged 1 commit into from Mar 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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