Skip to content

Commit

Permalink
Fix Style/RedundantSelfAssignmentBranch to handle heredocs
Browse files Browse the repository at this point in the history
  • Loading branch information
r7kamura committed Aug 19, 2023
1 parent dd29994 commit 75580b3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12133](https://github.com/rubocop/rubocop/pull/12133): Fix `Style/RedundantSelfAssignmentBranch` to handle heredocs. ([@r7kamura][])
5 changes: 5 additions & 0 deletions lib/rubocop/cop/style/redundant_self_assignment_branch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 75580b3

Please sign in to comment.