module Jsonapi::Sort::ClassMethods

Public Instance Methods

apply_sort(params = {}, options = { allowed: [], default: {} }) click to toggle source
# File lib/jsonapi/scopes/sorts.rb, line 21
def apply_sort(params = {}, options = { allowed: [], default: {} })
  fields = params.dig(:sort)

  allowed_fields = (Array.wrap(options[:allowed]).presence || @sortable_fields).map(&:to_sym)
  default_order = (options[:default].presence || @default_sort).transform_keys(&:to_sym)
  ordered_fields = convert_to_ordered_hash(fields)

  ordered_fields.each do |field, _|
    raise InvalidAttributeError, "#{field} is not valid as sort attribute." unless allowed_fields.include?(field)
  end

  order = ordered_fields.presence || default_order

  self.order(order)
end
default_sort(sort) click to toggle source
# File lib/jsonapi/scopes/sorts.rb, line 13
def default_sort(sort)
  @default_sort = sort
end
sortable_fields(*fields) click to toggle source
# File lib/jsonapi/scopes/sorts.rb, line 17
def sortable_fields(*fields)
  @sortable_fields = fields
end

Private Instance Methods

convert_to_ordered_hash(fields) click to toggle source
# File lib/jsonapi/scopes/sorts.rb, line 39
def convert_to_ordered_hash(fields)
  fields = fields.to_s.split(',').map(&:squish)

  fields.each_with_object({}) do |field, hash|
    if field.start_with?('-')
      field = field[1..-1]
      hash[field] = :desc
    else
      hash[field] = :asc
    end
  end.transform_keys(&:to_sym)
end