Skip to content

Commit

Permalink
Merge pull request rubocop#12697 from koic/fix_an_error_for_style_cas…
Browse files Browse the repository at this point in the history
…e_like_if

[Fix rubocop#12690] Fix an error for `Style/CaseLikeIf`
  • Loading branch information
koic committed Feb 17, 2024
2 parents 9746727 + dc74ac8 commit b5cccc7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_style_case_like_if.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12690](https://github.com/rubocop/rubocop/issues/12690): Fix an error for `Style/CaseLikeIf` when using `==` with literal and using ternary operator. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/case_like_if.rb
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def condition_from_binary_op(lhs, rhs, target)

def branch_conditions(node)
conditions = []
while node&.if_type?
while node&.if_type? && !node.ternary?
conditions << node.condition
node = node.else_branch
end
Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/style/case_like_if_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,26 @@
RUBY
end

it 'registers an offense when using `==` with literal and using ternary operator' do
expect_offense(<<~RUBY)
if foo == 1
^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif foo == 2
else
foo == 3 ? bar : baz
end
RUBY

expect_correction(<<~RUBY)
case foo
when 1
when 2
else
foo == 3 ? bar : baz
end
RUBY
end

it 'does not register an offense when using `==` with method call with arguments' do
expect_no_offenses(<<~RUBY)
if x == foo(1)
Expand Down

0 comments on commit b5cccc7

Please sign in to comment.