Module: JSONAPI::Utils::Support::Sort

Included in:
Response::Support
Defined in:
lib/jsonapi/utils/support/sort.rb

Instance Method Summary collapse

Instance Method Details

#apply_sort(records) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/jsonapi/utils/support/sort.rb', line 5

def apply_sort(records)
  return records unless params[:sort].present?

  if records.is_a?(Array)
    records.sort { |a, b| comp = 0; eval(sort_criteria) }
  elsif records.respond_to?(:order)
    records.order(sort_params)
  end
end

#sort_criteriaObject



15
16
17
18
19
20
21
# File 'lib/jsonapi/utils/support/sort.rb', line 15

def sort_criteria
  sort_params.reduce('') do |sum, hash|
    foo = ["a[:#{hash[0]}]", "b[:#{hash[0]}]"]
    foo.reverse! if hash[1] == :desc
    sum + "comp = comp == 0 ? #{foo.join(' <=> ')} : comp; "
  end
end

#sort_paramsObject



23
24
25
26
27
28
29
30
31
# File 'lib/jsonapi/utils/support/sort.rb', line 23

def sort_params
  @_sort_params ||=
    if params[:sort].present?
      params[:sort].split(',').each_with_object({}) do |criteria, hash|
        order, field = criteria.match(/(\-?)(\w+)/i)[1..2]
        hash[field]  = order == '-' ? :desc : :asc
      end
    end
end