Class: RESTFramework::ModelOrderingFilter

Inherits:
BaseFilter
  • Object
show all
Defined in:
lib/rest_framework/filters/model_ordering.rb

Overview

A filter backend which handles ordering of the recordset.

Instance Method Summary collapse

Methods inherited from BaseFilter

#initialize

Constructor Details

This class inherits a constructor from RESTFramework::BaseFilter

Instance Method Details

#_get_fieldsObject

Get a list of ordering fields for the current action.



4
5
6
# File 'lib/rest_framework/filters/model_ordering.rb', line 4

def _get_fields
  return @controller.ordering_fields&.map(&:to_s) || @controller.get_fields
end

#_get_orderingObject

Convert ordering string to an ordering configuration.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rest_framework/filters/model_ordering.rb', line 9

def _get_ordering
  return nil if @controller.ordering_query_param.blank?

  # Ensure ordering_fields are strings since the split param will be strings.
  fields = self._get_fields
  order_string = @controller.params[@controller.ordering_query_param]

  if order_string.present?
    ordering = {}.with_indifferent_access
    order_string.split(",").each do |field|
      if field[0] == "-"
        column = field[1..-1]
        direction = :desc
      else
        column = field
        direction = :asc
      end

      next if !column.in?(fields) && column.split(".").first.in?(fields)

      ordering[column] = direction
    end
    return ordering
  end

  return nil
end

#get_filtered_data(data) ⇒ Object

Order data according to the request query parameters.



38
39
40
41
42
43
44
45
46
47
# File 'lib/rest_framework/filters/model_ordering.rb', line 38

def get_filtered_data(data)
  ordering = self._get_ordering
  reorder = !@controller.ordering_no_reorder

  if ordering && !ordering.empty?
    return data.send(reorder ? :reorder : :order, ordering)
  end

  return data
end