class RuboCop::Cop::Style::GuardClause
ok
raise ‘exception’ if something
# good
end
ok
else
raise ‘exception’
if something
# bad
end
work if something
def test
# also good
end
work
return unless something
def test
# good
end
end
work
if something
def test
# bad
@example
expression
Use a guard clause instead of wrapping the code inside a conditional
def accepted_form?(node, ending = false)
def accepted_form?(node, ending = false) accepted_if?(node, ending) || node.condition.multiline? end
def accepted_if?(node, ending)
def accepted_if?(node, ending) return true if node.modifier_form? || node.ternary? if ending node.else? else !node.else? || node.elsif? end end
def check_ending_if(node)
def check_ending_if(node) return if accepted_form?(node, true) || !min_body_length?(node) add_offense(node, location: :keyword) end
def contains_guard_clause?(node)
def contains_guard_clause?(node) node.if_branch && node.if_branch.guard_clause? || node.else_branch && node.else_branch.guard_clause? end
def on_def(node)
def on_def(node) body = node.body return unless body if body.if_type? check_ending_if(body) elsif body.begin_type? && body.children.last.if_type? check_ending_if(body.children.last) end end
def on_if(node)
def on_if(node) return if accepted_form?(node) || !contains_guard_clause?(node) add_offense(node, location: :keyword) end