Sha256: 8a364f09d9231b42ed704acad190c40e276e2f08b23f62c18c36a896d21be6f0

Contents?: true

Size: 1.3 KB

Versions: 12

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop is used to identify usages of `ancestors.include?` and
      # change them to use `<=` instead.
      #
      # @example
      #   # bad
      #   A.ancestors.include?(B)
      #
      #   # good
      #   A <= B
      #
      class AncestorsInclude < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Use `<=` instead of `ancestors.include?`.'
        RESTRICT_ON_SEND = %i[include?].freeze

        def_node_matcher :ancestors_include_candidate?, <<~PATTERN
          (send (send $_subclass :ancestors) :include? $_superclass)
        PATTERN

        def on_send(node)
          return unless (subclass, superclass = ancestors_include_candidate?(node))
          return if subclass && !subclass.const_type?

          add_offense(range(node)) do |corrector|
            subclass_source = subclass ? subclass.source : 'self'

            corrector.replace(node, "#{subclass_source} <= #{superclass.source}")
          end
        end

        private

        def range(node)
          location_of_ancestors = node.children[0].loc.selector.begin_pos
          end_location = node.loc.selector.end_pos

          range_between(location_of_ancestors, end_location)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
rubocop-performance-1.11.5 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.11.4 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.11.3 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.11.2 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.11.1 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.11.0 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.10.2 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.10.1 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.10.0 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.9.2 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.9.1 lib/rubocop/cop/performance/ancestors_include.rb
rubocop-performance-1.9.0 lib/rubocop/cop/performance/ancestors_include.rb