BigW Consortium Gitlab

sortable.rb 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
# == Sortable concern
#
# Set default scope for ordering objects
#
module Sortable
  extend ActiveSupport::Concern

  included do
    # By default all models should be ordered
    # by created_at field starting from newest
11
    default_scope { order_id_desc }
12

13
    scope :order_id_desc, -> { reorder(id: :desc) }
14
    scope :order_id_asc, -> { reorder(id: :asc) }
15 16 17 18
    scope :order_created_desc, -> { reorder(created_at: :desc) }
    scope :order_created_asc, -> { reorder(created_at: :asc) }
    scope :order_updated_desc, -> { reorder(updated_at: :desc) }
    scope :order_updated_asc, -> { reorder(updated_at: :asc) }
19 20
    scope :order_name_asc, -> { reorder(name: :asc) }
    scope :order_name_desc, -> { reorder(name: :desc) }
21 22 23
  end

  module ClassMethods
24
    def order_by(method)
25
      case method.to_s
26
      when 'name_asc' then order_name_asc
27
      when 'name_desc' then order_name_desc
28 29 30 31
      when 'updated_asc' then order_updated_asc
      when 'updated_desc' then order_updated_desc
      when 'created_asc' then order_created_asc
      when 'created_desc' then order_created_desc
32 33
      when 'id_desc' then order_id_desc
      when 'id_asc' then order_id_asc
34
      else
35
        all
36 37
      end
    end
Felipe Artur committed
38 39 40

    private

41
    def highest_label_priority(target_type_column: nil, target_type: nil, target_column:, project_column:, excluded_labels: [])
42 43 44 45 46 47
      query = Label.select(LabelPriority.arel_table[:priority].minimum).
        left_join_priorities.
        joins(:label_links).
        where("label_priorities.project_id = #{project_column}").
        where("label_links.target_id = #{target_column}").
        reorder(nil)
Felipe Artur committed
48

Douwe Maan committed
49 50 51 52 53 54
      query =
        if target_type_column
          query.where("label_links.target_type = #{target_type_column}")
        else
          query.where(label_links: { target_type: target_type })
        end
55 56

      query = query.where.not(title: excluded_labels) if excluded_labels.present?
Felipe Artur committed
57 58 59

      query
    end
60 61
  end
end