Module: Cuprum::Collections::Queries::Ordering

Defined in:
lib/cuprum/collections/queries/ordering.rb

Overview

Functionality around validating and normalizing query sort orderings.

Defined Under Namespace

Classes: InvalidOrderError

Class Method Summary collapse

Class Method Details

.normalize(*attributes, ordering_hash = nil) ⇒ Hash

Converts the given sort order into a hash with standard values.

Parameters:

  • attributes (Array<String, Symbol>)

    The attribute names to sort by, in ascending direction, and in order of importance.

  • ordering_hash (Hash) (defaults to: nil)

    An optional ordering hash, with keys that are valid attribute names and values that are valid sort directions.

Returns:

  • (Hash)

    the normalized sort ordering.

Raises:

  • InvalidOrderError if any of the attributes are invalid attribute names.

  • InvalidOrderError if any of the hash keys are invalid attribute names, or any of the hash values are invalid sort directions.



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cuprum/collections/queries/ordering.rb', line 35

def normalize(*attributes)
  attributes = attributes.flatten if attributes.first.is_a?(Array)

  validate_ordering!(attributes)

  qualified = attributes.last.is_a?(Hash) ? attributes.pop : {}
  qualified = normalize_order_hash(qualified)

  attributes
    .each
    .with_object({}) { |attribute, hsh| hsh[attribute.intern] = :asc }
    .merge(qualified)
end