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 Style/RedundantSelfAssignmentBranch to handle heredocs #12133

Merged
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
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