Class: ActiveSet::Sorting::EnumerableStrategy

Inherits:
Object
  • Object
show all
Defined in:
lib/active_set/sorting/enumerable_strategy.rb

Instance Method Summary collapse

Constructor Details

#initialize(set, attribute_instructions) ⇒ EnumerableStrategy

Returns a new instance of EnumerableStrategy.



9
10
11
12
13
14
15
# File 'lib/active_set/sorting/enumerable_strategy.rb', line 9

def initialize(set, attribute_instructions)
  @set = set
  @attribute_instructions = attribute_instructions
  @set_instructions = attribute_instructions.map do |attribute_instruction|
    EnumerableSetInstruction.new(attribute_instruction, set)
  end
end

Instance Method Details

#direction_multiplier(direction) ⇒ Object



46
47
48
49
50
# File 'lib/active_set/sorting/enumerable_strategy.rb', line 46

def direction_multiplier(direction)
  return -1 if direction.to_s.downcase.start_with? 'desc'

  1
end

#executeObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_set/sorting/enumerable_strategy.rb', line 17

def execute
  # http://brandon.dimcheff.com/2009/11/18/rubys-sort-vs-sort-by/
  @set.sort_by do |item|
    @set_instructions.map do |set_instruction|
      value_for_comparison = sortable_numeric_for(set_instruction, item)
      direction_multiplier = direction_multiplier(set_instruction.value)

      # When ActiveSet.configuration.on_asc_sort_nils_come == :last
      # null values to be sorted as if larger than any non-null value.
      # ASC => [-2, -1, 1, 2, nil]
      # DESC => [nil, 2, 1, -1, -2]
      # Otherwise sort nulls as if smaller than any non-null value.
      # ASC => [nil, -2, -1, 1, 2]
      # DESC => [2, 1, -1, -2, nil]
      if value_for_comparison.nil?
        [direction_multiplier * nil_sorter, 0]
      else
        [0, value_for_comparison * direction_multiplier]
      end
    end
  end
end

#nil_sorterObject



52
53
54
55
56
# File 'lib/active_set/sorting/enumerable_strategy.rb', line 52

def nil_sorter
  return 1 if ActiveSet.configuration.on_asc_sort_nils_come == :last

  -1
end

#sortable_numeric_for(set_instruction, item) ⇒ Object



40
41
42
43
44
# File 'lib/active_set/sorting/enumerable_strategy.rb', line 40

def sortable_numeric_for(set_instruction, item)
  value = set_instruction.attribute_value_for(item)

  transform_to_sortable_numeric(value)
end