123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::InvertibleUnlessCondition

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/invertible_unless_condition.rb

Overview

Checks for usages of unless which can be replaced by if with inverted condition. Code without unless is easier to read, but that is subjective, so this cop is disabled by default.

Methods that can be inverted should be defined in InverseMethods. Note that the relationship of inverse methods needs to be defined in both directions. For example,

InverseMethods:
  :!=: :==
  :even?: :odd?
  :odd?: :even?

will suggest both even? and odd? to be inverted, but only != (and not ==).

Examples:

# bad (simple condition)
foo unless !bar
foo unless x != y
foo unless x >= 10
foo unless x.even?
foo unless odd?

# good
foo if bar
foo if x == y
foo if x < 10
foo if x.odd?
foo if even?

# bad (complex condition)
foo unless x != y || x.even?

# good
foo if x == y && x.odd?

# good (if)
foo if !condition

Cop Safety Information:

  • This cop is unsafe because it cannot be guaranteed that the method and its inverse method are both defined on receiver, and also are actually inverse of each other.

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

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.

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

Returns a url to view this cops documentation online.

.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::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

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Instance Method Details

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 133

def autocorrect(corrector, node)
  case node.type
  when :begin
    autocorrect(corrector, node.children.first)
  when :send
    autocorrect_send_node(corrector, node)
  when :or, :and
    corrector.replace(node.loc.operator, node.inverse_operator)
    autocorrect(corrector, node.lhs)
    autocorrect(corrector, node.rhs)
  end
end

#autocorrect_send_node(corrector, node) (private)

[ GitHub ]

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

def autocorrect_send_node(corrector, node)
  if node.method?(:!)
    corrector.remove(node.loc.selector)
  else
    corrector.replace(node.loc.selector, inverse_methods[node.method_name])
  end
end

#inheritance_check?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 90

def inheritance_check?(node)
  argument = node.first_argument
  node.method?(:<) &&
    (argument.const_type? && argument.short_name.to_s.upcase != argument.short_name.to_s)
end

#inverse_methods (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 154

def inverse_methods
  @inverse_methods ||= cop_config['InverseMethods']
end

#invertible?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 75

def invertible?(node) # rubocop:disable Metrics/CyclomaticComplexity
  case node&.type
  when :begin
    invertible?(node.children.first)
  when :send
    return false if inheritance_check?(node)

    node.method?(:!) || inverse_methods.key?(node.method_name)
  when :or, :and
    invertible?(node.lhs) && invertible?(node.rhs)
  else
    false
  end
end

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 58

def on_if(node)
  return unless node.unless?

  condition = node.condition
  return unless invertible?(condition)

  message = format(MSG, prefer: "#{node.inverse_keyword} #{preferred_condition(condition)}",
                        current: "#{node.keyword} #{condition.source}")

  add_offense(node, message: message) do |corrector|
    corrector.replace(node.loc.keyword, node.inverse_keyword)
    autocorrect(corrector, condition)
  end
end

#preferred_condition(node) (private)

[ GitHub ]

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

def preferred_condition(node)
  case node.type
  when :begin    then "(#{preferred_condition(node.children.first)})"
  when :send     then preferred_send_condition(node)
  when :or, :and then preferred_logical_condition(node)
  end
end

#preferred_logical_condition(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/invertible_unless_condition.rb', line 126

def preferred_logical_condition(node)
  preferred_lhs = preferred_condition(node.lhs)
  preferred_rhs = preferred_condition(node.rhs)

  "#{preferred_lhs} #{node.inverse_operator} #{preferred_rhs}"
end

#preferred_send_condition(node) (private)

[ GitHub ]

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

def preferred_send_condition(node) # rubocop:disable Metrics/CyclomaticComplexity
  receiver_source = node.receiver&.source
  return receiver_source if node.method?(:!)

  # receiver may be implicit (self)
  dotted_receiver_source = receiver_source ? "#{receiver_source}." : ''

  inverse_method_name = inverse_methods[node.method_name]
  return "#{dotted_receiver_source}#{inverse_method_name}" unless node.arguments?

  argument_list = node.arguments.map(&:source).join(', ')
  if node.operator_method?
    return "#{receiver_source} #{inverse_method_name} #{argument_list}"
  end

  if node.parenthesized?
    return "#{dotted_receiver_source}#{inverse_method_name}(#{argument_list})"
  end

  "#{dotted_receiver_source}#{inverse_method_name} #{argument_list}"
end