Class: Warped::Queries::Sort

Inherits:
Object
  • Object
show all
Defined in:
lib/warped/queries/sort.rb

Overview

Sorts a scope by a given key and direction

This class provides a way to sort a scope by a given key and direction. It uses the reorder method to sort the scope, so it will remove any existing order.

Examples:

Sort a scope by a key and direction

Warped::Queries::Sort.call(User.all, sort_key: "name", sort_direction: "asc")
# => #<ActiveRecord::Relation [...]>

Sort a scope by a key with format table.column and direction

Warped::Queries::Sort.call(User.join(:accounts), sort_key: "accounts.updated_at", sort_direction: "asc")
# => #<ActiveRecord::Relation [...]>

Constant Summary collapse

SORT_DIRECTIONS =
%w[asc desc].freeze
NULLS_SORT_DIRECTION =
%w[asc_nulls_first asc_nulls_last desc_nulls_first desc_nulls_last].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, sort_key:, sort_direction: :desc) ⇒ ActiveRecord::Relation

Returns the sorted scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to sort

  • sort_key (String, Symbol)

    the key to sort by

  • sort_direction (String, Symbol) (defaults to: :desc)

    the direction to sort by



36
37
38
39
40
41
# File 'lib/warped/queries/sort.rb', line 36

def initialize(scope, sort_key:, sort_direction: :desc)
  super()
  @scope = scope
  @sort_key = sort_key.to_s
  @sort_direction = sort_direction.to_s.downcase
end

Class Method Details

.call(scope, sort_key:, sort_direction: :desc) ⇒ ActiveRecord::Relation

Returns the sorted scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to sort

  • sort_key (String, Symbol)

    the key to sort by

  • sort_direction (String, Symbol) (defaults to: :desc)

    the direction to sort by

Returns:

  • (ActiveRecord::Relation)

    the sorted scope



28
29
30
# File 'lib/warped/queries/sort.rb', line 28

def self.call(scope, sort_key:, sort_direction: :desc)
  new(scope, sort_key:, sort_direction:).call
end

Instance Method Details

#callActiveRecord::Relation

Returns:

  • (ActiveRecord::Relation)


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/warped/queries/sort.rb', line 44

def call
  validate_sort_direction!(sort_direction)

  order = if NULLS_SORT_DIRECTION.include?(sort_direction)
            arel_order
          else
            { sort_key => sort_direction }
          end

  scope.reorder(order)
end