Skip to content

Commit

Permalink
[Fix rubocop#7795] Make Layout/EmptyLineAfterGuardClause aware of `…
Browse files Browse the repository at this point in the history
…and return`

Resolves rubocop#7795.

This PR makes `Layout/EmptyLineAfterGuardClause` aware of `and return`.

It was proposed based on the following code controlled by Rails
controller.

```ruby
render :foo and return if condition

do_something
```

I think that it can be generalized as a control flow.

```ruby
foo(arg) and return if condition

do_something
```

So it will be newly detected by `Layout/EmptyLineAfterGuardClause` cop.
  • Loading branch information
koic committed Mar 19, 2020
1 parent ff8f827 commit 2e9f9e2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
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

0 comments on commit 2e9f9e2

Please sign in to comment.