Sha256: a504e0a71743e927f48ba1dcc883cdc00a9e9a504bfa47e5539351448107e6cf

Contents?: true

Size: 1.13 KB

Versions: 11

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Identifies places where `sort_by { ... }` can be replaced by
      # `sort`.
      #
      # @example
      #   # bad
      #   array.sort_by { |x| x }
      #   array.sort_by do |var|
      #     var
      #   end
      #
      #   # good
      #   array.sort
      class RedundantSortBy < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Use `sort` instead of `sort_by { |%<var>s| %<var>s }`.'

        # @!method redundant_sort_by(node)
        def_node_matcher :redundant_sort_by, <<~PATTERN
          (block $(send _ :sort_by) (args (arg $_x)) (lvar _x))
        PATTERN

        def on_block(node)
          redundant_sort_by(node) do |send, var_name|
            range = sort_by_range(send, node)

            add_offense(range, message: format(MSG, var: var_name)) do |corrector|
              corrector.replace(range, 'sort')
            end
          end
        end

        private

        def sort_by_range(send, node)
          range_between(send.loc.selector.begin_pos, node.loc.end.end_pos)
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.31.2/lib/rubocop/cop/style/redundant_sort_by.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.31.2/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.34.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.34.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.33.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.32.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.31.2 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.31.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.31.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.30.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.30.0 lib/rubocop/cop/style/redundant_sort_by.rb