Class: Warped::Queries::Sort
- Inherits:
-
Object
- Object
- Warped::Queries::Sort
- 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.
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
-
.call(scope, sort_key:, sort_direction: :desc) ⇒ ActiveRecord::Relation
The sorted scope.
Instance Method Summary collapse
- #call ⇒ ActiveRecord::Relation
-
#initialize(scope, sort_key:, sort_direction: :desc) ⇒ ActiveRecord::Relation
constructor
The sorted scope.
Constructor Details
#initialize(scope, sort_key:, sort_direction: :desc) ⇒ ActiveRecord::Relation
Returns the sorted scope.
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.
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
#call ⇒ 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 |