class RuboCop::Cop::Style::GuardClause
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 check_if_node(node)
def check_if_node(node) _cond, body, else_body = *node return if body && else_body # discard modifier ifs and ternary_ops return if modifier_if?(node) || ternary_op?(node) # discard short ifs return unless min_body_length?(node) add_offense(node, :keyword, MSG) end
def if?(body)
def if?(body) body && body.type == :if end
def min_body_length
def min_body_length length = cop_config['MinBodyLength'] || 1 return length if length.is_a?(Integer) && length > 0 fail 'MinBodyLength needs to be a positive integer!' end
def min_body_length?(node)
def min_body_length?(node) (node.loc.end.line - node.loc.keyword.line) > min_body_length end
def on_def(node)
def on_def(node) _, _, body = *node return unless body if if?(body) check_if_node(body) elsif body.type == :begin expressions = *body last_expr = expressions.last check_if_node(last_expr) if if?(last_expr) end end