Sha256: 13706c83676b06c8c945bf9d65f3e67226482da086eeed03fef9a43aebde659d

Contents?: true

Size: 1.52 KB

Versions: 8

Compression:

Stored size: 1.52 KB

Contents

module Plucky
  module Normalizers
    class SortValue

      # Public: Initializes a Plucky::Normalizers::SortValue
      #
      # args - The hash of arguments
      #        :key_normalizer - What to use to normalize keys, must
      #                          respond to call.
      #
      def initialize(args = {})
        @key_normalizer = args.fetch(:key_normalizer) {
          raise ArgumentError, "Missing required key :key_normalizer"
        }
      end

      # Public: Given a value returns it normalized for Mongo's sort option
      def call(value)
        case value
          when Array
            if value.size == 1 && value[0].is_a?(String)
              normalized_sort_piece(value[0])
            else
              value.compact.map { |v| normalized_sort_piece(v).flatten }
            end
          else
            normalized_sort_piece(value)
        end
      end

      # Private
      def normalized_sort_piece(value)
        case value
          when SymbolOperator
            [normalized_direction(value.field, value.operator)]
          when String
            value.split(',').map do |piece|
              normalized_direction(*piece.split(' '))
            end
          when Symbol
            [normalized_direction(value)]
          else
            value
        end
      end

      # Private
      def normalized_direction(field, direction=nil)
        direction ||= 'ASC'
        direction = direction.upcase == 'ASC' ? 1 : -1
        [@key_normalizer.call(field).to_s, direction]
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
plucky-0.7.0 lib/plucky/normalizers/sort_value.rb
plucky-0.6.6 lib/plucky/normalizers/sort_value.rb
plucky-0.6.5 lib/plucky/normalizers/sort_value.rb
plucky-0.6.4 lib/plucky/normalizers/sort_value.rb
plucky-0.6.3 lib/plucky/normalizers/sort_value.rb
plucky-0.6.2 lib/plucky/normalizers/sort_value.rb
plucky-0.6.1 lib/plucky/normalizers/sort_value.rb
plucky-0.6.0 lib/plucky/normalizers/sort_value.rb