Class: Toller::Sorts::ScopeHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/toller/sorts/scope_handler.rb

Overview

Scope handler for sort

Instance Method Summary collapse

Instance Method Details

#call(collection, direction, properties) ⇒ ActiveRecord::Relation

Applies a named scope to collection for a type: :scope sort.

If the resolved scope doesn't exist on the collection's model, the sort is logged and skipped instead of raising a NoMethodError.

Parameters:

  • collection (ActiveRecord::Relation)

    the collection to sort

  • direction (Symbol)

    the sort direction, :asc or :desc, passed to the scope

  • properties (Hash)

    the sort's properties, used to resolve :scope_name (falling back to :field)

Returns:

  • (ActiveRecord::Relation)

    the scoped collection, or collection unchanged if the scope is unknown



19
20
21
22
23
24
25
26
27
28
# File 'lib/toller/sorts/scope_handler.rb', line 19

def call(collection, direction, properties)
  scoped_name = properties[:scope_name] || properties[:field]

  unless collection.klass.respond_to?(scoped_name)
    Rails.logger.warn("[Toller] Skipping sort: #{collection.klass} has no scope `#{scoped_name}`")
    return collection
  end

  collection.public_send(scoped_name, direction)
end