Class: Rubocop::Cop::LineBreakAfterGuardClauses

Inherits:
RuboCop::Cop::Base
  • Object
show all
Extended by:
RuboCop::Cop::AutoCorrector
Defined in:
lib/rubocop/cop/line_break_after_guard_clauses.rb

Overview

Ensures a line break after guard clauses.

Examples:

# bad
return unless condition
do_stuff

# good
return unless condition

do_stuff

# bad
raise if condition
do_stuff

# good
raise if condition

do_stuff

Multiple guard clauses are allowed without
line break.

# good
return unless condition_a
return unless condition_b

do_stuff

Guard clauses in case statement are allowed without
line break.

# good
case model
  when condition_a
    return true unless condition_b
  when
    ...
end

Guard clauses before end are allowed without
line break.

# good
if condition_a
  do_something
else
  do_something_else
  return unless condition
end

do_something_more

Constant Summary collapse

MSG =
'Add a line break after guard clauses'

Instance Method Summary collapse

Instance Method Details

#guard_clause_node?(node) ⇒ Object



64
65
66
# File 'lib/rubocop/cop/line_break_after_guard_clauses.rb', line 64

def_node_matcher :guard_clause_node?, <<-PATTERN
  [{(send nil? {:raise :fail :throw} ...) return break next} single_line?]
PATTERN

#on_if(node) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/rubocop/cop/line_break_after_guard_clauses.rb', line 68

def on_if(node)
  return unless node.single_line?
  return unless guard_clause?(node)
  return if next_line(node).blank? || clause_last_line?(next_line(node)) || guard_clause?(next_sibling(node))

  add_offense(node) do |corrector|
    corrector.insert_after(node, "\n")
  end
end