Skip to content

Commit

Permalink
Merge pull request #12570 from koic/fix_an_error_for_style_identical_…
Browse files Browse the repository at this point in the history
…conditional_branches

[Fix #12569] Fix an error for `Style/IdenticalConditionalBranches`
  • Loading branch information
koic committed Dec 26, 2023
2 parents 9fb1e25 + 9cd8136 commit 94d14fe
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12569](https://github.com/rubocop/rubocop/issues/12569): Fix an error for `Style/IdenticalConditionalBranches` when using `if`...`else` with identical leading lines that assign to `self.foo`. ([@koic][])
5 changes: 4 additions & 1 deletion lib/rubocop/cop/style/identical_conditional_branches.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ def check_branches(node, branches)
if head.assignment?
# The `send` node is used instead of the `indexasgn` node, so `name` cannot be used.
# https://github.com/rubocop/rubocop-ast/blob/v1.29.0/lib/rubocop/ast/node/indexasgn_node.rb
assigned_value = head.send_type? ? head.receiver.source : head.name.to_s
#
# FIXME: It would be better to update `RuboCop::AST::OpAsgnNode` or its subclasses to
# handle `self.foo ||= value` as a solution, instead of using `head.node_parts[0].to_s`.
assigned_value = head.send_type? ? head.receiver.source : head.node_parts[0].to_s

return if condition_variable == assigned_value
end
Expand Down
25 changes: 25 additions & 0 deletions spec/rubocop/cop/style/identical_conditional_branches_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,31 @@
end
end

context 'on if...else with identical leading lines and assign to `self.foo`' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if something
self.foo ||= default
^^^^^^^^^^^^^^^^^^^^ Move `self.foo ||= default` out of the conditional.
do_x
else
self.foo ||= default
^^^^^^^^^^^^^^^^^^^^ Move `self.foo ||= default` out of the conditional.
do_y
end
RUBY

expect_correction(<<~RUBY)
self.foo ||= default
if something
do_x
else
do_y
end
RUBY
end
end

context 'on if..else with identical leading lines and assign to condition value of method call receiver' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
Expand Down

0 comments on commit 94d14fe

Please sign in to comment.