123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RedundantCondition

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/redundant_condition.rb

Overview

Checks for unnecessary conditional expressions.

Examples:

# bad
a = b ? b : c

# good
a = b || c
# bad
if b
  b
else
  c
end

# good
b || c

# good
if b
  b
elsif cond
  c
end

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

.builtin?

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Cops (other than builtin) are encouraged to implement this.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range, #reset_investigation, #use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#argument_with_operator?(argument) ⇒ Boolean (private)

If the argument is using an operator, it is an invalid syntax. e.g. foo || *bar, foo || **bar, and foo || &bar.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 167

def argument_with_operator?(argument)
  return true if ARGUMENT_WITH_OPERATOR_TYPES.include?(argument.type)
  return false unless argument.hash_type?
  return false unless (node = argument.children.first)

  node.kwsplat_type? || node.forwarded_kwrestarg_type?
end

#asgn_type?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 142

def asgn_type?(node)
  node.lvasgn_type? || node.ivasgn_type? || node.cvasgn_type? || node.gvasgn_type?
end

#branches_have_assignment?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 132

def branches_have_assignment?(node)
  _condition, if_branch, else_branch = *node

  return false unless if_branch && else_branch

  asgn_type?(if_branch) && (if_branch_variable_name = if_branch.name) &&
    asgn_type?(else_branch) && (else_branch_variable_name = else_branch.name) &&
    if_branch_variable_name == else_branch_variable_name
end

#branches_have_method?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 146

def branches_have_method?(node)
  _condition, if_branch, else_branch = *node

  return false unless if_branch && else_branch

  single_argument_method?(if_branch) && single_argument_method?(else_branch) &&
    same_method?(if_branch, else_branch)
end

#correct_ternary(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 240

def correct_ternary(corrector, node)
  corrector.replace(range_of_offense(node), '||')

  return unless node.else_branch.range_type?

  corrector.wrap(node.else_branch, '(', ')')
end

#else_source(else_branch, arithmetic_operation) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 187

def else_source(else_branch, arithmetic_operation) # rubocop:disable Metrics/AbcSize
  if arithmetic_operation
    "#{else_branch.first_argument.source})"
  elsif branches_have_method?(else_branch.parent)
    else_source_if_has_method(else_branch)
  elsif require_parentheses?(else_branch)
    "(#{else_branch.source})"
  elsif without_argument_parentheses_method?(else_branch)
    "#{else_branch.method_name}(#{else_branch.arguments.map(&:source).join(', ')})"
  elsif branches_have_assignment?(else_branch.parent)
    else_source_if_has_assignment(else_branch)
  else
    else_branch.source
  end
end

#else_source_if_has_assignment(else_branch) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 213

def else_source_if_has_assignment(else_branch)
  if require_parentheses?(else_branch.expression)
    "(#{else_branch.expression.source})"
  elsif require_braces?(else_branch.expression)
    "{ #{else_branch.expression.source} }"
  else
    else_branch.expression.source
  end
end

#else_source_if_has_method(else_branch) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 203

def else_source_if_has_method(else_branch)
  if require_parentheses?(else_branch.first_argument)
    "(#{else_branch.first_argument.source})"
  elsif require_braces?(else_branch.first_argument)
    "{ #{else_branch.first_argument.source} }"
  else
    else_branch.first_argument.source
  end
end

#if_source(if_branch, arithmetic_operation) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 175

def if_source(if_branch, arithmetic_operation)
  if branches_have_method?(if_branch.parent) && if_branch.parenthesized?
    if_branch.source.delete_suffix(')')
  elsif arithmetic_operation
    argument_source = if_branch.first_argument.source

    "#{if_branch.receiver.source} #{if_branch.method_name} (#{argument_source}"
  else
    if_branch.source
  end
end

#make_ternary_form(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 223

def make_ternary_form(node)
  _condition, if_branch, else_branch = *node
  arithmetic_operation = use_arithmetic_operation?(if_branch)

  ternary_form = [
    if_source(if_branch, arithmetic_operation),
    else_source(else_branch, arithmetic_operation)
  ].join(' || ')
  ternary_form += ')' if branches_have_method?(node) && if_branch.parenthesized?

  if node.parent&.send_type?
    "(#{ternary_form})"
  else
    ternary_form
  end
end

#message(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 64

def message(node)
  if redundant_condition?(node)
    REDUNDANT_CONDITION
  else
    MSG
  end
end

#offense?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 79

def offense?(node)
  _condition, _if_branch, else_branch = *node

  return false if use_if_branch?(else_branch) || use_hash_key_assignment?(else_branch)

  synonymous_condition_and_branch?(node) && !node.elsif? &&
    (node.ternary? || !else_branch.instance_of?(AST::Node) || else_branch.single_line?)
end

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 43

def on_if(node)
  return if node.elsif_conditional?
  return unless offense?(node)

  message = message(node)

  add_offense(range_of_offense(node), message: message) do |corrector|
    if node.ternary? && !branches_have_method?(node)
      correct_ternary(corrector, node)
    elsif redundant_condition?(node)
      corrector.replace(node, node.if_branch.source)
    else
      corrected = make_ternary_form(node)

      corrector.replace(node, corrected)
    end
  end
end

#range_of_offense(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 72

def range_of_offense(node)
  return node.source_range unless node.ternary?
  return node.source_range if node.ternary? && branches_have_method?(node)

  range_between(node.loc.question.begin_pos, node.loc.colon.end_pos)
end

#redundant_condition?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 88

def redundant_condition?(node)
  node.modifier_form? || !node.else_branch
end

#require_braces?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 255

def require_braces?(node)
  node.hash_type? && !node.braces?
end

#require_parentheses?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 248

def require_parentheses?(node)
  (node.basic_conditional? && node.modifier_form?) ||
    node.range_type? ||
    node.rescue_type? ||
    (node.respond_to?(:semantic_operator?) && node.semantic_operator?)
end

#same_method?(if_branch, else_branch) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 161

def same_method?(if_branch, else_branch)
  if_branch.method?(else_branch.method_name) && if_branch.receiver == else_branch.receiver
end

#single_argument_method?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 155

def single_argument_method?(node)
  return false if !node.send_type? || node.method?(:[]) || !node.arguments.one?

  !argument_with_operator?(node.first_argument)
end

#synonymous_condition_and_branch?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 104

def synonymous_condition_and_branch?(node)
  condition, if_branch, _else_branch = *node
  # e.g.
  #   if var
  #     var
  #   else
  #     'foo'
  #   end
  return true if condition == if_branch

  # e.g.
  #   if foo
  #     @value = foo
  #   else
  #     @value = another_value?
  #   end
  return true if branches_have_assignment?(node) && condition == if_branch.expression

  # e.g.
  #   if foo
  #     test.value = foo
  #   else
  #     test.value = another_value?
  #   end
  branches_have_method?(node) && condition == if_branch.first_argument &&
    !use_hash_key_access?(if_branch)
end

#use_arithmetic_operation?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 259

def use_arithmetic_operation?(node)
  node.respond_to?(:arithmetic_operation?) && node.arithmetic_operation?
end

#use_hash_key_access?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 100

def use_hash_key_access?(node)
  node.send_type? && node.method?(:[])
end

#use_hash_key_assignment?(else_branch) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 96

def use_hash_key_assignment?(else_branch)
  else_branch&.send_type? && else_branch&.method?(:[]=)
end

#use_if_branch?(else_branch) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 92

def use_if_branch?(else_branch)
  else_branch&.if_type?
end

#without_argument_parentheses_method?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_condition.rb', line 263

def without_argument_parentheses_method?(node)
  node.send_type? && !node.arguments.empty? &&
    !node.parenthesized? && !node.operator_method? && !node.assignment_method?
end