Module: Jsonapi::QueryBuilder::Mixins::Filter

Extended by:
ActiveSupport::Concern
Included in:
BaseQuery
Defined in:
lib/jsonapi/query_builder/mixins/filter.rb

Instance Method Summary collapse

Instance Method Details

#filter(collection, filter_params = send(:filter_params)) ⇒ ActiveRecord::Relation, Array

Filters the passed relation with the default filter params (parsed from the queries params) or with explicitly passed filter parameters. Iterates through registered filters so that the filter application order is settable from the backend side instead of being dependent on the query order from the clients. If the filter condition for the filter strategy is met, then the filter is applied to the collection. If the strategy responds to a call method it calls it with the collection and parameter’s parsed sort direction, otherwise it instantiates the filter class with the collection and the parameter’s query value and calls for the results.

Parameters:

  • collection (ActiveRecord::Relation)
  • filter_params (Object) (defaults to: send(:filter_params))

    Optional explicit filter params

Returns:

  • (ActiveRecord::Relation, Array)

    An AR relation is returned unless filters need to resort to in-memory filtering strategy, then an array is returned.



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/jsonapi/query_builder/mixins/filter.rb', line 60

def filter(collection, filter_params = send(:filter_params))
  self.class.supported_filters.reduce(collection) do |filtered_collection, supported_filter|
    filter, options = serialize_filter(supported_filter, collection: filtered_collection, params: filter_params)

    next filtered_collection unless options[:conditions].all? { |type, condition|
      check_condition(condition, type, filter: filter, query: options[:query])
    }

    filter.respond_to?(:call) ? filter.call(filtered_collection, options[:query]) : filter.results
  end
end