Module: Trailblazer::Finder::Adapters::Basic::Sorting

Defined in:
lib/trailblazer/finder/adapters/basic/sorting.rb

Overview

Basic Paging Adapter

Class Method Summary collapse

Class Method Details

.set_sorting_handlerObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/trailblazer/finder/adapters/basic/sorting.rb', line 12

def set_sorting_handler
  ->(sort_attributes, entity) do
    sort_attributes.delete(:handler)
    attributes = []
    sort_attributes.each do |attr|
      attributes << [attr[0].to_sym, (attr[1] == :asc ? 1 : -1)]
    end
    entity.sort do |this, that|
      attributes.reduce(0) do |diff, order|
        next diff if diff != 0 # this and that have differed at an earlier order entry

        key, direction = order
        # deal with nil cases
        next  0 if this[key].nil? && that[key].nil?
        next  1 if this[key].nil?
        next -1 if that[key].nil?

        # do the actual comparison
        comparison = this[key] <=> that[key]
        comparison * direction
      end
    end
  end
end