diff --git a/changelog/fix_style_redundant_self_assignment_branch_to_handle_heredocs.md b/changelog/fix_style_redundant_self_assignment_branch_to_handle_heredocs.md new file mode 100644 index 000000000000..1b363a0b6449 --- /dev/null +++ b/changelog/fix_style_redundant_self_assignment_branch_to_handle_heredocs.md @@ -0,0 +1 @@ +* [#12133](https://github.com/rubocop/rubocop/pull/12133): Fix `Style/RedundantSelfAssignmentBranch` to handle heredocs. ([@r7kamura][]) diff --git a/lib/rubocop/cop/style/redundant_self_assignment_branch.rb b/lib/rubocop/cop/style/redundant_self_assignment_branch.rb index cb0aec73bd1c..3340094e0606 100644 --- a/lib/rubocop/cop/style/redundant_self_assignment_branch.rb +++ b/lib/rubocop/cop/style/redundant_self_assignment_branch.rb @@ -75,6 +75,11 @@ def register_offense(if_node, offense_branch, opposite_branch, keyword) add_offense(offense_branch) do |corrector| assignment_value = opposite_branch ? opposite_branch.source : 'nil' replacement = "#{assignment_value} #{keyword} #{if_node.condition.source}" + if opposite_branch.respond_to?(:heredoc?) && opposite_branch.heredoc? + replacement += opposite_branch.loc.heredoc_end.with( + begin_pos: opposite_branch.source_range.end_pos + ).source + end corrector.replace(if_node, replacement) end diff --git a/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb b/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb index 9b57e2313532..0c63eafc769e 100644 --- a/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb +++ b/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb @@ -93,6 +93,25 @@ RUBY end + it 'registers and corrects an offense when self-assigning redundant if branch with heredoc' do + expect_offense(<<~RUBY) + foo = if condition + foo + ^^^ Remove the self-assignment branch. + else + <<~TEXT + bar + TEXT + end + RUBY + + expect_correction(<<~RUBY) + foo = <<~TEXT unless condition + bar + TEXT + RUBY + end + it 'does not register an offense when self-assigning redundant else branch and multiline if branch' do expect_no_offenses(<<~RUBY) foo = if condition