Class: RESTFramework::ModelFilter
- Inherits:
-
BaseFilter
- Object
- BaseFilter
- RESTFramework::ModelFilter
- 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
-
#_get_fields ⇒ Object
Get a list of filterset fields for the current action.
-
#_get_filter_params ⇒ Object
Filter params for keys allowed by the current action’s filterset_fields/fields config.
-
#get_filtered_data(data) ⇒ Object
Filter data according to the request query parameters.
Methods inherited from BaseFilter
Constructor Details
This class inherits a constructor from RESTFramework::BaseFilter
Instance Method Details
#_get_fields ⇒ Object
Get a list of filterset fields for the current action. Fallback to columns because we don’t want to try filtering by any query parameter because that could clash with other query parameters.
16 17 18 19 20 |
# File 'lib/rest_framework/filters.rb', line 16 def _get_fields return @_get_fields ||= ( @controller.class.filterset_fields || @controller.get_fields(fallback: true) ).map(&:to_s) end |
#_get_filter_params ⇒ Object
Filter params for keys allowed by the current action’s filterset_fields/fields config.
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 53 54 55 |
# File 'lib/rest_framework/filters.rb', line 23 def _get_filter_params # Map filterset fields to strings because query parameter keys are strings. 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.
58 59 60 61 62 63 64 |
# File 'lib/rest_framework/filters.rb', line 58 def get_filtered_data(data) if filter_params = self._get_filter_params.presence return data.where(**filter_params) end return data end |