Class: Plucky::Normalizers::SortValue

Inherits:
Object
  • Object
show all
Defined in:
lib/plucky/normalizers/sort_value.rb

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ SortValue

Public: Initializes a Plucky::Normalizers::SortValue

args - The hash of arguments

:key_normalizer - What to use to normalize keys, must
                  respond to call.


11
12
13
14
15
# File 'lib/plucky/normalizers/sort_value.rb', line 11

def initialize(args = {})
  @key_normalizer = args.fetch(:key_normalizer) {
    raise ArgumentError, "Missing required key :key_normalizer"
  }
end

Instance Method Details

#call(value) ⇒ Object

Public: Given a value returns it normalized for Mongo’s sort option



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/plucky/normalizers/sort_value.rb', line 18

def call(value)
  case value
    when Array
      if value.size == 1 && value[0].is_a?(String)
        normalized_sort_piece(value[0])
      else
        value.compact.inject({}) { |acc, v| acc.merge(normalized_sort_piece(v)) }
      end
    else
      normalized_sort_piece(value)
  end
end

#normalized_direction(field, direction = nil) ⇒ Object

Private



50
51
52
53
54
# File 'lib/plucky/normalizers/sort_value.rb', line 50

def normalized_direction(field, direction=nil)
  direction ||= 'ASC'
  direction = direction.upcase == 'ASC' ? 1 : -1
  {@key_normalizer.call(field).to_s => direction}
end

#normalized_sort_piece(value) ⇒ Object

Private



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/plucky/normalizers/sort_value.rb', line 32

def normalized_sort_piece(value)
  case value
    when SymbolOperator
      normalized_direction(value.field, value.operator)
    when String
      value.split(',').inject({}) do |acc, piece|
        acc.merge(normalized_direction(*piece.split(' ')))
      end
    when Symbol
      normalized_direction(value)
    when Array
      Hash[*value]
    else
      value
  end
end