Class: Graphiti::Scoping::Sort

Inherits:
Base show all
Defined in:
lib/graphiti/scoping/sort.rb

Overview

Apply sorting logic to the scope.

By default, sorting comes ‘for free’. To specify a custom sorting proc:

class PostResource < ApplicationResource
  sort do |scope, att, dir|
    int = dir == :desc ? -1 : 1
    scope.sort_by { |x| x[att] * int }
  end
end

The sorting proc will be called once for each sort att/dir requested.

See Also:

  • Resource.sort

Instance Attribute Summary

Attributes inherited from Base

#query_hash, #resource

Instance Method Summary collapse

Methods inherited from Base

#apply, #apply?, #initialize

Constructor Details

This class inherits a constructor from Graphiti::Scoping::Base

Instance Method Details

#apply_custom_scopeObject

Apply custom scoping proc configured via Resource DSL

Returns:

  • the scope we are chaining/modifying



43
44
45
46
47
48
49
# File 'lib/graphiti/scoping/sort.rb', line 43

def apply_custom_scope
  each_sort do |attribute, direction|
    @scope = custom_scope
      .call(@scope, attribute, direction, resource.context)
  end
  @scope
end

#apply_standard_scopeObject

Apply default scope logic via Resource adapter

Returns:

  • the scope we are chaining/modifying



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/graphiti/scoping/sort.rb', line 23

def apply_standard_scope
  each_sort do |attribute, direction|
    resource.get_attr!(attribute, :sortable, request: true)
    sort = resource.sorts[attribute]
    if sort[:only] && sort[:only] != direction
      raise Errors::UnsupportedSort.new resource,
        attribute, sort[:only], direction
    else
      @scope = if sort[:proc]
        resource.instance_exec(@scope, direction, &sort[:proc])
      else
        resource.adapter.order(@scope, attribute, direction)
      end
    end
  end
  @scope
end

#custom_scopeProc, Nil

Returns The custom proc specified by Resource DSL.

Returns:

  • (Proc, Nil)

    The custom proc specified by Resource DSL



17
18
19
# File 'lib/graphiti/scoping/sort.rb', line 17

def custom_scope
  resource.sort_all
end