Class: RESTFramework::ModelFilter

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

Overview

A simple filtering backend that supports filtering a recordset based on fields defined on the controller class.

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 filterset fields for the current action.



15
16
17
18
# File 'lib/rest_framework/filters.rb', line 15

def _get_fields
  # Always return a list of strings; `@controller.get_fields` already does this.
  return @controller.class.filterset_fields&.map(&:to_s) || @controller.get_fields
end

#_get_filter_paramsObject

Filter params for keys allowed by the current action’s filterset_fields/fields config.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rest_framework/filters.rb', line 21

def _get_filter_params
  fields = self._get_fields

  return @controller.request.query_parameters.select { |p, _|
    # Remove any trailing `__in` from the field name.
    field = p.chomp("__in")

    # Remove any associations whose sub-fields are not filterable.
    if match = /(.*)\.(.*)/.match(field)
      field, sub_field = match[1..2]
      next false unless field.in?(fields)

      sub_fields = @controller.class.get_field_config(field)[:sub_fields] || []
      next sub_field.in?(sub_fields)
    end

    next field.in?(fields)
  }.map { |p, v|
    # Convert fields ending in `__in` to array values.
    if p.end_with?("__in")
      p = p.chomp("__in")
      v = v.split(",")
    end

    # Convert "nil" and "null" to nil.
    if v == "nil" || v == "null"
      v = nil
    end

    [p, v]
  }.to_h.symbolize_keys
end

#get_filtered_data(data) ⇒ Object

Filter data according to the request query parameters.



55
56
57
58
59
60
61
# File 'lib/rest_framework/filters.rb', line 55

def get_filtered_data(data)
  if filter_params = self._get_filter_params.presence
    return data.where(**filter_params)
  end

  return data
end