lib/rubocop/cop/style/non_nil_check.rb in rubocop-0.21.0 vs lib/rubocop/cop/style/non_nil_check.rb in rubocop-0.22.0
- old
+ new
@@ -7,13 +7,16 @@
#
# @example
#
# # bad
# if x != nil
+ #
+ # # good (when not allowing semantic changes)
+ # # bad (when allowing semantic changes)
# if !x.nil?
#
- # # good
+ # # good (when allowing semantic changes)
# if x
#
# Non-nil checks are allowed if they are the final nodes of predicate.
#
# # good
@@ -41,17 +44,21 @@
return unless [:!=, :!].include?(method)
if method == :!=
add_offense(node, :selector) if args == NIL_NODE
- elsif method == :!
+ elsif include_semantic_changes? && method == :!
add_offense(node, :expression) if nil_check?(receiver)
end
end
private
+ def include_semantic_changes?
+ cop_config['IncludeSemanticChanges']
+ end
+
def process_method(name, body)
# only predicate methods are handled differently
return unless name.to_s.end_with?('?')
return unless body
@@ -80,10 +87,15 @@
end
def autocorrect_comparison(node)
@corrections << lambda do |corrector|
expr = node.loc.expression
- new_code = expr.source.sub(/\s*!=\s*nil/, '')
+ new_code =
+ if include_semantic_changes?
+ expr.source.sub(/\s*!=\s*nil/, '')
+ else
+ expr.source.sub(/^(\S*)\s*!=\s*nil/, '!\1.nil?')
+ end
corrector.replace(expr, new_code)
end
end
def autocorrect_non_nil(node, inner_node)