123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::InverseMethods

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

Overview

Checks for usages of not (not or !) called on a method when an inverse of that method can be used instead.

Methods that can be inverted by a not (not or !) should be defined in InverseMethods.

Methods that are inverted by inverting the return of the block that is passed to the method should be defined in InverseBlocks.

Examples:

# bad
!foo.none?
!foo.any? { |f| f.even? }
!foo.blank?
!(foo == bar)
foo.select { |f| !f.even? }
foo.reject { |f| f != 7 }

# good
foo.none?
foo.blank?
foo.any? { |f| f.even? }
foo != bar
foo == bar
!!('foo' =~ /^\w+$/)
!(foo.class < Numeric) # Checking class hierarchy is allowed
# Blocks with guard clauses are ignored:
foo.select do |f|
  next if f.zero?
  f != 1
end

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

DEPARTMENT_SEVERITIES, 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.

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

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

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

transform

Instance Attribute Summary

::RuboCop::Cop::Base - Inherited

::RuboCop::Cop::AutocorrectLogic - Included

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?,
#skipped_unsafe_correction_with_disable_uncorrectable?

Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while --disable-uncorrectable asks for a todo comment on everything this run cannot correct.

#contextual_autocorrect_held_back?

When LSP is enabled or the --editor-mode option is on, it is considered as editing source code, and autocorrection with AutoCorrect: contextual will not be performed.

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#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

rubocop:disable-next Metrics/ParameterLists.

#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

 — grouped under the Commissioner heading above.

#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_gem_version

Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked).

#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, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 56

def self.autocorrect_incompatible_with
  [Style::Not, Style::SymbolProc]
end

Instance Method Details

#binary_operator?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 140

def binary_operator?(node)
  node.operator_method? && !node.loc.dot && !node.method?(:[]) && !node.method?(:[]=)
end

#camel_case_constant?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 202

def camel_case_constant?(node)
  node.const_type? && CAMEL_CASE.match?(node.source)
end

#correct_inverse_block(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 144

def correct_inverse_block(corrector, node)
  method_call, method, block = inverse_block?(node)

  corrector.replace(method_call.loc.selector, inverse_blocks[method].to_s)
  correct_inverse_selector(block, corrector)
end

#correct_inverse_method(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 113

def correct_inverse_method(corrector, node)
  method_call, _lhs, method, _rhs = inverse_candidate?(node)
  return unless method_call && method

  remove_negation(corrector, node, method, method_call)
  corrector.replace(method_call.loc.selector, inverse_methods[method].to_s)
end

#correct_inverse_selector(block, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 151

def correct_inverse_selector(block, corrector)
  selector_loc = block.loc.selector
  selector = selector_loc.source

  if NEGATED_EQUALITY_METHODS.include?(selector.to_sym)
    selector[0] = '='
    corrector.replace(selector_loc, selector)
  else
    if block.loc.dot
      range = dot_range(block.loc)
      corrector.remove(range)
    end

    corrector.remove(selector_loc)
  end
end

#dot_range(loc) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 206

def dot_range(loc)
  range_between(loc.dot.begin_pos, loc.expression.end_pos)
end

#end_parentheses(node, method_call) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 185

def end_parentheses(node, method_call)
  method_call.source_range.end.join(node.source_range.end)
end

#inverse_block?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 70

def_node_matcher :inverse_block?, <<~PATTERN
  (any_block $(call (...) $_) ... { $(call ... :!)
                                    $(send (...) {:!= :!~} ...)
                                    (begin ... $(call ... :!))
                                    (begin ... $(send (...) {:!= :!~} ...))
                                  })
PATTERN

#inverse_blocks (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 173

def inverse_blocks
  @inverse_blocks ||= cop_config['InverseBlocks'].merge(cop_config['InverseBlocks'].invert)
end

#inverse_candidate?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 61

def_node_matcher :inverse_candidate?, <<~PATTERN
  {
    (send $(call $(...) $_ $...) :!)
    (send (any_block $(call $(...) $_) $...) :!)
    (send (begin $(call $(...) $_ $...)) :!)
  }
PATTERN

#inverse_methods (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 168

def inverse_methods
  @inverse_methods ||= cop_config['InverseMethods']
                       .merge(cop_config['InverseMethods'].invert)
end

#keep_parentheses?(node, method_call) ⇒ Boolean (private)

[ GitHub ]

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

def keep_parentheses?(node, method_call)
  return false unless node.receiver.begin_type? || node.parenthesized?
  return false unless method_call.operator_method?
  return false unless (parent = node.parent)&.call_type?

  binary_operator?(parent) || parent.receiver.equal?(node)
end

#message(method, inverse) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 216

def message(method, inverse)
  format(MSG, method: method, inverse: inverse)
end

#negated?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 177

def negated?(node)
  node.parent.respond_to?(:method?) && node.parent.method?(:!)
end

#not_to_receiver(node, method_call) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 181

def not_to_receiver(node, method_call)
  node.loc.selector.begin.join(method_call.source_range.begin)
end

#on_block(node) Also known as: #on_numblock, #on_itblock

[ GitHub ]

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

def on_block(node)
  inverse_block?(node) do |_method_call, method, block|
    return unless inverse_blocks.key?(method)
    return if negated?(node) && negated?(node.parent)
    return if node.each_node(:next).any?

    # Inverse method offenses inside of the block of an inverse method
    # offense, such as `y.reject { |key, _value| !(key =~ /c\d/) }`,
    # can cause autocorrection to apply improper corrections.
    ignore_node(block)
    add_offense(node, message: message(method, inverse_blocks[method])) do |corrector|
      correct_inverse_block(corrector, node)
    end
  end
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

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

alias on_csend on_send

#on_itblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 109

alias on_itblock on_block

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 108

alias on_numblock on_block

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 78

def on_send(node)
  inverse_candidate?(node) do |method_call, lhs, method, rhs|
    return unless inverse_methods.key?(method)
    return if negated?(node) || safe_navigation_incompatible?(method_call)
    return if part_of_ignored_node?(node)
    return if possible_class_hierarchy_check?(lhs, rhs, method)

    add_offense(node, message: message(method, inverse_methods[method])) do |corrector|
      correct_inverse_method(corrector, node)
    end
  end
end

#possible_class_hierarchy_check?(lhs, rhs, method) ⇒ Boolean (private)

When comparing classes, !(Integer < Numeric) is not the same as Integer > Numeric.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 197

def possible_class_hierarchy_check?(lhs, rhs, method)
  CLASS_COMPARISON_METHODS.include?(method) &&
    (camel_case_constant?(lhs) || (rhs.size == 1 && camel_case_constant?(rhs.first)))
end

#remove_end_parenthesis(corrector, node, method, method_call) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 210

def remove_end_parenthesis(corrector, node, method, method_call)
  return unless EQUALITY_METHODS.include?(method) || method_call.parent.begin_type?

  corrector.remove(end_parentheses(node, method_call))
end

#remove_negation(corrector, node, method, method_call) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 121

def remove_negation(corrector, node, method, method_call)
  if !keep_parentheses?(node, method_call)
    corrector.remove(not_to_receiver(node, method_call))
    remove_end_parenthesis(corrector, node, method, method_call)
  elsif node.parenthesized?
    corrector.remove(node.loc.selector)
  else
    corrector.remove(node.loc.selector.join(node.receiver.source_range.begin))
  end
end

#safe_navigation_incompatible?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 189

def safe_navigation_incompatible?(node)
  return false unless node.csend_type?

  SAFE_NAVIGATION_INCOMPATIBLE_METHODS.include?(node.method_name)
end