BigW Consortium Gitlab

sortable.rb 1.61 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 41 42 43 44 45 46 47 48 49 50 51

    private

    def highest_label_priority(object_types, condition_field, excluded_labels: [])
      query = Label.select(Label.arel_table[:priority].minimum).
        joins(:label_links).
        where(label_links: { target_type: object_types }).
        where("label_links.target_id = #{condition_field}").
        reorder(nil)

      query.where.not(title: excluded_labels) if excluded_labels.present?

      query
    end
52 53
  end
end