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 #7795] Make Layout/EmptyLineAfterGuardClause aware of and return #7796

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
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
* [#7793](https://github.com/rubocop-hq/rubocop/pull/7793): Prefer `include?` over `member?` in `Style/CollectionMethods`. ([@dmolesUC][])
* [#7654](https://github.com/rubocop-hq/rubocop/issues/7654): Support `with_fixed_indentation` option for `Layout/ArrayAlignment` cop. ([@nikitasakov][])
* [#7783](https://github.com/rubocop-hq/rubocop/pull/7783): Support Ruby 2.7's numbered parameter for `Style/RedundantSort`. ([@koic][])
* [#7795](https://github.com/rubocop-hq/rubocop/issues/7795): Make `Layout/EmptyLineAfterGuardClause` aware of case where `and` or `or` is used before keyword that break control (e.g. `and return`). ([@koic][])

### Bug fixes

Expand Down
8 changes: 7 additions & 1 deletion lib/rubocop/ast/node.rb
Expand Up @@ -469,7 +469,13 @@ def range_type?
irange_type? || erange_type?
end

def_node_matcher :guard_clause?, <<~PATTERN
def guard_clause?
node = and_type? || or_type? ? rhs : self

node.match_guard_clause?
end

def_node_matcher :match_guard_clause?, <<~PATTERN
[${(send nil? {:raise :fail} ...) return break next} single_line?]
PATTERN

Expand Down
38 changes: 38 additions & 0 deletions spec/rubocop/cop/layout/empty_line_after_guard_clause_spec.rb
Expand Up @@ -163,6 +163,44 @@ def foo
RUBY
end

it 'registers an offense and corrects when using `and return` ' \
'before guard condition' do
expect_offense(<<~RUBY)
def foo
render :foo and return if condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
do_something
end
RUBY

expect_correction(<<~RUBY)
def foo
render :foo and return if condition

do_something
end
RUBY
end

it 'registers an offense and corrects when using `or return` ' \
'before guard condition' do
expect_offense(<<~RUBY)
def foo
render :foo or return if condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
do_something
end
RUBY

expect_correction(<<~RUBY)
def foo
render :foo or return if condition

do_something
end
RUBY
end

it 'accepts modifier if' do
expect_no_offenses(<<~RUBY)
def foo
Expand Down