Sha256: b005bf9bb5eaef7930b05aaebb29ecc6e5b4cf7b93847d7cbab93675ecdac98e

Contents?: true

Size: 1.54 KB

Versions: 44

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # Checks for places where ordering by `id` column is used.
      #
      # Don't use the `id` column for ordering. The sequence of ids is not guaranteed
      # to be in any particular order, despite often (incidentally) being chronological.
      # Use a timestamp column to order chronologically. As a bonus the intent is clearer.
      #
      # NOTE: Make sure the changed order column does not introduce performance
      # bottlenecks and appropriate database indexes are added.
      #
      # @example
      #   # bad
      #   scope :chronological, -> { order(id: :asc) }
      #   scope :chronological, -> { order(primary_key => :asc) }
      #
      #   # good
      #   scope :chronological, -> { order(created_at: :asc) }
      #
      class OrderById < Base
        include RangeHelp

        MSG = 'Do not use the `id` column for ordering. Use a timestamp column to order chronologically.'
        RESTRICT_ON_SEND = %i[order].freeze

        def_node_matcher :order_by_id?, <<~PATTERN
          (send _ :order
            {
              (sym :id)
              (hash (pair (sym :id) _))
              (send _ :primary_key)
              (hash (pair (send _ :primary_key) _))
            })
        PATTERN

        def on_send(node)
          add_offense(offense_range(node)) if order_by_id?(node)
        end

        private

        def offense_range(node)
          range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
        end
      end
    end
  end
end

Version data entries

44 entries across 41 versions & 7 rubygems

Version Path
rubocop-rails-2.16.1 lib/rubocop/cop/rails/order_by_id.rb
rubocop-rails-2.16.0 lib/rubocop/cop/rails/order_by_id.rb
rubocop-rails-2.15.2 lib/rubocop/cop/rails/order_by_id.rb
rubocop-rails-2.15.1 lib/rubocop/cop/rails/order_by_id.rb