milestone_array.rb 1.02 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
module MilestoneArray
  class << self
    def sort(array, sort_method)
      case sort_method
      when 'due_date_asc'
        sort_asc_nulls_last(array, 'due_date')
      when 'due_date_desc'
        sort_desc_nulls_last(array, 'due_date')
      when 'start_date_asc'
        sort_asc_nulls_last(array, 'start_date')
      when 'start_date_desc'
        sort_desc_nulls_last(array, 'start_date')
      when 'name_asc'
        sort_asc(array, 'title')
      when 'name_desc'
18
        sort_asc(array, 'title').reverse
19 20 21 22 23 24 25 26
      else
        array
      end
    end

    private

    def sort_asc_nulls_last(array, attribute)
27 28 29
      attribute = attribute.to_sym

      array.select(&attribute).sort_by(&attribute) + array.reject(&attribute)
30 31 32
    end

    def sort_desc_nulls_last(array, attribute)
33 34 35
      attribute = attribute.to_sym

      array.select(&attribute).sort_by(&attribute).reverse + array.reject(&attribute)
36 37 38 39 40 41 42
    end

    def sort_asc(array, attribute)
      array.sort_by(&attribute.to_sym)
    end
  end
end