class RuboCop::Cop::Style::ReturnNilInPredicateMethodDefinition
end
do_something?
return if condition
def foo?
# good
@example AllowedPatterns: [/foo/]
end
do_something?
return if condition
def foo?
# good
@example AllowedMethods: [‘foo?’]
end
do_something?
return false if condition
def foo?
# good
end
do_something?
return nil if condition
def foo?
# bad
end
do_something?
return if condition
def foo?
# bad
@example
from ‘nil` to `false` could potentially lead to incompatibility issues.
Autocorrection is marked as unsafe because the change of the return value
@safety
Checks if `return` or `return nil` is used in predicate method definitions.
def nil_node_at_the_end_of_method_body(body)
def nil_node_at_the_end_of_method_body(body) return body if body.nil_type? return unless body.begin_type? return unless (last_child = body.children.last) last_child if last_child.is_a?(AST::Node) && last_child.nil_type? end
def on_def(node)
def on_def(node) return unless node.predicate_method? return if allowed_method?(node.method_name) || matches_allowed_pattern?(node.method_name) return unless (body = node.body) body.each_descendant(:return) do |return_node| register_offense(return_node, 'return false') if return_nil?(return_node) end return unless (nil_node = nil_node_at_the_end_of_method_body(body)) register_offense(nil_node, 'false') end
def register_offense(offense_node, replacement)
def register_offense(offense_node, replacement) add_offense(offense_node) do |corrector| corrector.replace(offense_node, replacement) end end