Skip to content

Commit

Permalink
[Fix rubocop#12221] Fix a false positive for `Layout/EmptyLineAfterGu…
Browse files Browse the repository at this point in the history
…ardClause`

Fixes rubocop#12221.

This PR fixes a false positive for `Layout/EmptyLineAfterGuardClause`
when using `return` before guard condition with heredoc.
  • Loading branch information
koic committed Sep 26, 2023
1 parent c626229 commit 9b04830
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12221](https://github.com/rubocop/rubocop/issues/12221): Fix a false positive for `Layout/EmptyLineAfterGuardClause` when using `return` before guard condition with heredoc. ([@koic][])
8 changes: 8 additions & 0 deletions lib/rubocop/cop/layout/empty_line_after_guard_clause.rb
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ def last_heredoc_argument_node(node)

if node.if_branch.and_type?
node.if_branch.children.first
elsif use_heredoc_in_condition?(node.condition)
node.condition
else
node.if_branch.children.last
end
Expand All @@ -180,6 +182,12 @@ def heredoc?(node)
node.respond_to?(:heredoc?) && node.heredoc?
end

def use_heredoc_in_condition?(condition)
condition.descendants.any? do |descendant|
descendant.respond_to?(:heredoc?) && descendant.heredoc?
end
end

def offense_location(node)
if node.loc.respond_to?(:end) && node.loc.end
node.loc.end
Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/cop/layout/empty_line_after_guard_clause_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,30 @@ def foo
RUBY
end

it 'does not register an offense and corrects when using `return` before guard condition with heredoc' do
expect_no_offenses(<<~RUBY)
def foo
return true if <<~TEXT.length > bar
hi
TEXT
false
end
RUBY
end

it 'does not register an offense and corrects when using `raise` before guard condition with heredoc' do
expect_no_offenses(<<~RUBY)
def foo
raise if <<~TEXT.length > bar
hi
TEXT
baz
end
RUBY
end

it 'registers an offense and corrects a guard clause that is a ternary operator' do
expect_offense(<<~RUBY)
def foo
Expand Down

0 comments on commit 9b04830

Please sign in to comment.