Class: RuboCop::Cop::Guardrails::ExplicitConditional

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/guardrails/explicit_conditional.rb

Overview

Flags conditionals that rely on bare truthiness instead of an explicit predicate method. ‘if user` hides the real question: are you checking for nil, blank, empty, or something else? Pick the predicate that says what you mean.

Examples:

# bad
do_something if user
return unless 

# good
do_something if user.present?
return unless .nil?

Constant Summary collapse

MSG_IF =
'Use a predicate method (e.g. `present?`) instead of a bare truthiness check.'
MSG_UNLESS =
'Use `nil?` instead of a bare truthiness check.'
COMPARISON_OPERATORS =
%i[== != < > <= >= <=> =~ !~ === !].to_set.freeze
VARIABLE_TYPES =
%i[lvar ivar cvar gvar].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#on_if(node) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/rubocop/cop/guardrails/explicit_conditional.rb', line 26

def on_if(node)
  unless node.ternary?
    condition = unwrap_begin(node.condition)
    if bare_check?(condition)
      add_offense(condition, message: node.unless? ? MSG_UNLESS : MSG_IF)
    end
  end
end