Sha256: 00c71c5cb8882c28f332f5b600bf13979077e1d41b2e8b9cd3d35a679ea32f10

Contents?: true

Size: 1.21 KB

Versions: 14

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

14 entries across 14 versions & 2 rubygems

Version Path
zuora_connect_ui-0.10.0 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.9.2 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.9.1 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.9.0 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.8.3 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.8.2 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.8.1 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.8.0 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.7.1 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
zuora_connect_ui-0.7.0 vendor/ruby/2.6.0/gems/rubocop-0.72.0/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.72.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.71.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.70.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-0.69.0 lib/rubocop/cop/style/redundant_sort_by.rb