Sha256: 3cc4095b33d7e223e677bd070f191cce59c4940c340654e434a3e08a62dd4d80

Contents?: true

Size: 1.39 KB

Versions: 32

Compression:

Stored size: 1.39 KB

Contents

module JsonapiCompliable
  # 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 Resource.sort
  class Scoping::Sort < Scoping::Base
    # @return [Proc, Nil] The custom proc specified by Resource DSL
    def custom_scope
      resource.sorting
    end

    # Apply default scope logic via Resource adapter
    # @return the scope we are chaining/modifying
    def apply_standard_scope
      each_sort do |attribute, direction|
        @scope = resource.adapter.order(@scope, attribute, direction)
      end
      @scope
    end

    # Apply custom scoping proc configured via Resource DSL
    # @return the scope we are chaining/modifying
    def apply_custom_scope
      each_sort do |attribute, direction|
        @scope = custom_scope.call(@scope, attribute, direction)
      end
      @scope
    end

    private

    def each_sort
      sort_param.each do |sort_hash|
        yield sort_hash.keys.first, sort_hash.values.first
      end
    end

    def sort_param
      @sort_param ||= query_hash[:sort].empty? ? resource.default_sort : query_hash[:sort]
    end
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
jsonapi_compliable-0.11.1 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.11.0 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.9 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.7 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.6 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.5 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.4 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.3 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.2 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.1 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.10.0 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.9.2 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.9.1 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.9.0 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.8.0 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.7.9 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.7.8 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.7.7 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.7.6 lib/jsonapi_compliable/scoping/sort.rb
jsonapi_compliable-0.7.5 lib/jsonapi_compliable/scoping/sort.rb