Skip to content

Commit

Permalink
[Fix #9977] Update Layout/EmptyLineAfterGuardClause to not register…
Browse files Browse the repository at this point in the history
… an offense if there is another expression following the guard clause on the same line.
  • Loading branch information
dvandersluis authored and mergify[bot] committed Aug 5, 2021
1 parent 6d46406 commit 984fcea
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_skip_autocorrection_for.md
@@ -0,0 +1 @@
* [#9977](https://github.com/rubocop/rubocop/issues/9977): Update `Layout/EmptyLineAfterGuardClause` to not register an offense if there is another expression following the guard clause on the same line. ([@dvandersluis][])
9 changes: 9 additions & 0 deletions lib/rubocop/cop/layout/empty_line_after_guard_clause.rb
Expand Up @@ -38,12 +38,14 @@ module Layout
class EmptyLineAfterGuardClause < Base
include RangeHelp
extend AutoCorrector
extend Util

MSG = 'Add empty line after guard clause.'
END_OF_HEREDOC_LINE = 1

def on_if(node)
return if correct_style?(node)
return if multiple_statements_on_line?(node)

if node.modifier_form? && (heredoc_node = last_heredoc_argument(node))
return if next_line_empty_or_enable_directive_comment?(heredoc_line(node, heredoc_node))
Expand Down Expand Up @@ -166,6 +168,13 @@ def offense_location(node)
node
end
end

def multiple_statements_on_line?(node)
parent = node.parent
return false unless parent

parent.begin_type? && parent.single_line?
end
end
end
end
Expand Down
42 changes: 42 additions & 0 deletions spec/rubocop/cop/layout/empty_line_after_guard_clause_spec.rb
@@ -1,6 +1,12 @@
# frozen_string_literal: true

RSpec.describe RuboCop::Cop::Layout::EmptyLineAfterGuardClause, :config do
it 'does not register an offense when the clause is not followed by other code' do
expect_no_offenses(<<~RUBY)
return unless item.positive?
RUBY
end

it 'registers an offense and corrects a guard clause not followed by empty line' do
expect_offense(<<~RUBY)
def foo
Expand Down Expand Up @@ -560,4 +566,40 @@ def foo
end
RUBY
end

it 'does not register an offense when there are multiple clauses on the same line' do
expect_no_offenses(<<~RUBY)
def foo(item)
return unless item.positive?; item * 2
end
RUBY
end

it 'registers an offense when the clause ends with a semicolon but the next clause is on the next line' do
expect_offense(<<~RUBY)
def foo(item)
return unless item.positive?;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
item * 2
end
RUBY

expect_correction(<<~RUBY)
def foo(item)
return unless item.positive?;
item * 2
end
RUBY
end

it 'does not register an offense when the clause ends with a semicolon but is followed by a newline' do
expect_no_offenses(<<~RUBY)
def foo(item)
return unless item.positive?;
item * 2
end
RUBY
end
end

0 comments on commit 984fcea

Please sign in to comment.