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

Check 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

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

Actually private methods.

#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

#camel_case_constant?(node) ⇒ Boolean (private)

[ GitHub ]

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

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 121

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 112

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

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

#correct_inverse_selector(block, corrector) (private)

[ GitHub ]

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

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 181

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 166

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
  ({block numblock} $(call (...) $_) ... { $(call ... :!)
                                           $(send (...) {:!= :!~} ...)
                                           (begin ... $(call ... :!))
                                           (begin ... $(send (...) {:!= :!~} ...))
                                         })
PATTERN

#inverse_blocks (private)

[ GitHub ]

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

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 ({block numblock} $(call $(...) $_) $...) :!)
    (send (begin $(call $(...) $_ $...)) :!)
  }
PATTERN

#inverse_methods (private)

[ GitHub ]

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

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

#message(method, inverse) (private)

[ GitHub ]

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

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 154

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 162

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

[ 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_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) || relational_comparison_with_safe_navigation?(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 172

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

#relational_comparison_with_safe_navigation?(node) ⇒ Boolean (private)

[ GitHub ]

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

def relational_comparison_with_safe_navigation?(node)
  node.csend_type? && CLASS_COMPARISON_METHODS.include?(node.method_name)
end

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

[ GitHub ]

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

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