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) ⇒ ActiveRecord::Relation, Array

Apply sort on result set (ascending by default).

e.g.: User.order(:first_name)

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

Returns:

  • (ActiveRecord::Relation, Array)


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

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_criteriaString

Build the criteria to be evaluated wthen applying sort on Array of Hashes (ascending by default).

Returns:

  • (String)


28
29
30
31
32
33
34
35
# File 'lib/jsonapi/utils/support/sort.rb', line 28

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

#sort_paramsHash, NilClass

Build a Hash with the sort criteria.

Returns:

  • (Hash, NilClass)


42
43
44
45
46
47
48
49
50
51
# File 'lib/jsonapi/utils/support/sort.rb', line 42

def sort_params
  @_sort_params ||=
    if params[:sort].present?
      params[:sort].split(',').each_with_object({}) do |field, hash|
        unformatted_field  = @request.unformat_key(field)
        desc, field        = unformatted_field.to_s.match(/^([-_])?(\w+)$/i)[1..2]
        hash[field.to_sym] = desc.present? ? :desc : :asc
      end
    end
end