Class: RESTFramework::ModelOrderingFilter

Inherits:
BaseFilter
  • Object
show all
Defined in:
lib/rest_framework/filters.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. Do not fallback to columns in case the user wants to order by a virtual column.



45
46
47
# File 'lib/rest_framework/filters.rb', line 45

def _get_fields
  return @controller.class.ordering_fields || @controller.get_fields
end

#_get_orderingObject

Convert ordering string to an ordering configuration.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rest_framework/filters.rb', line 50

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

  # Ensure ordering_fields are strings since the split param will be strings.
  fields = self._get_fields&.map(&:to_s)
  order_string = @controller.params[@controller.class.ordering_query_param]

  if order_string.present? && fields
    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
      if !fields || column.in?(fields)
        ordering[column] = direction
      end
    end
    return ordering
  end

  return nil
end

#get_filtered_data(data) ⇒ Object

Order data according to the request query parameters.



78
79
80
81
82
83
84
85
86
87
# File 'lib/rest_framework/filters.rb', line 78

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

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

  return data
end