Class: JSONAPI::Support::Sort

Inherits:
Object
  • Object
show all
Defined in:
lib/json_api/support/sort.rb,
lib/json_api/support/sort/field.rb,
lib/json_api/support/sort/compare.rb

Overview

Applies sort parameters to a scope, handling database column sorts, scope-based sorts, and virtual attribute sorts (in-memory).

Validates sort_params against resource_class.permitted_sortable_fields eagerly in the constructor. Raises InvalidFieldError if any fields are not permitted — callers never need to validate separately.

Virtual sorts (resource instance methods) cannot be applied at the database level, so they are collected and applied last as an in-memory sort over the materialised result set. This means virtual sorts always take precedence over column/scope sorts regardless of the order the user specified them in.

Defined Under Namespace

Modules: Compare Classes: Field, InvalidFieldError

Instance Method Summary collapse

Constructor Details

#initialize(sort_params:, resource_class:) ⇒ Sort

Returns a new instance of Sort.



30
31
32
# File 'lib/json_api/support/sort.rb', line 30

def initialize(sort_params:, resource_class:)
  @fields = build_fields(sort_params, resource_class)
end

Instance Method Details

#apply(scope) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/json_api/support/sort.rb', line 34

def apply(scope)
  return scope if @fields.empty?

  virtual, db = @fields.partition(&:virtual?)
  scope = db.reduce(scope) { |acc, field| field.apply(acc) }
  virtual.any? ? apply_virtual_sorting(scope, virtual) : scope
end

#virtual_fields?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/json_api/support/sort.rb', line 42

def virtual_fields?
  @fields.any?(&:virtual?)
end