Class: RuboCop::Cop::InternalAffairs::LocationLineEqualityComparison

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb

Overview

This cop enforces the use of `same_line?` instead of location line comparison for equality.

Examples:

# bad
node.loc.line == node.parent.loc.line

# bad
node.loc.first_line == node.parent.loc.first_line

# good
same_line?(node, node.parent)

Constant Summary collapse

MSG =
'Use `%<preferred>s`.'

Constants inherited from Base

Base::RESTRICT_ON_SEND

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods inherited from Base

#add_global_offense, #add_offense, autocorrect_incompatible_with, badge, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, #cop_name, cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

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

Methods included from RuboCop::Cop::IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

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

Instance Method Details

#line_send(node) ⇒ Object


24
25
26
27
28
29
# File 'lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb', line 24

def_node_matcher :line_send, <<~PATTERN
  {
    (send (send _ {:loc :source_range}) {:line :first_line})
    (send _ :first_line)
  }
PATTERN

#location_line_equality_comparison?(node) ⇒ Object


32
33
34
# File 'lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb', line 32

def_node_matcher :location_line_equality_comparison?, <<~PATTERN
  (send #line_send :== #line_send)
PATTERN

#on_send(node) ⇒ Object


36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb', line 36

def on_send(node)
  return unless location_line_equality_comparison?(node)

  lhs, _op, rhs = *node

  lhs_receiver = extract_receiver(lhs)
  rhs_receiver = extract_receiver(rhs)
  preferred = "same_line?(#{lhs_receiver}, #{rhs_receiver})"

  add_offense(node, message: format(MSG, preferred: preferred)) do |corrector|
    corrector.replace(node, preferred)
  end
end