Sha256: 53edb6f67c7ee851ce558301cf080f608dd8904cb893866f8fce7b49dc6e73df

Contents?: true

Size: 1.21 KB

Versions: 51

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop 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 < Cop
        include RangeHelp

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

        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(node,
                        location: range,
                        message: format(MSG, var: var_name))
          end
        end

        def autocorrect(node)
          send = node.send_node
          ->(corrector) { corrector.replace(sort_by_range(send, node), 'sort') }
        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

51 entries across 39 versions & 5 rubygems

Version Path
rubocop-0.91.0 lib/rubocop/cop/style/redundant_sort_by.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/style/redundant_sort_by.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.90.0/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.90.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.89.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.89.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.88.0 lib/rubocop/cop/style/redundant_sort_by.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.87.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.87.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.86.0 lib/rubocop/cop/style/redundant_sort_by.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/redundant_sort_by.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/redundant_sort_by.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.85.1 lib/rubocop/cop/style/redundant_sort_by.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.85.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.84.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.83.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.82.0 lib/rubocop/cop/style/redundant_sort_by.rb