BigW Consortium Gitlab

sortable.rb 1.19 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 38 39
      end
    end
  end
end