Class: Brainstem::QueryStrategies::FilterAndSearch

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/brainstem/query_strategies/filter_and_search.rb

Instance Method Summary collapse

Methods inherited from BaseStrategy

#calculate_per_page, #evaluate_count, #evaluate_scope, #initialize

Constructor Details

This class inherits a constructor from Brainstem::QueryStrategies::BaseStrategy

Instance Method Details

#execute(scope) ⇒ Object



4
5
6
7
8
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
# File 'lib/brainstem/query_strategies/filter_and_search.rb', line 4

def execute(scope)
  scope, ordered_search_ids = run_search(scope, filter_includes.map(&:name))
  scope = @options[:primary_presenter].apply_filters_to_scope(scope, @options[:params], @options)

  if ordering?
    count_scope = scope
    scope = paginate(scope)
    scope = @options[:primary_presenter].apply_ordering_to_scope(scope, @options[:params])
    primary_models = evaluate_scope(scope)
    count = evaluate_count(count_scope)
  else
    filtered_ids = scope.pluck(:id)
    count = filtered_ids.size

    # order a potentially large set of ids
    ordered_ids = order_for_search(filtered_ids, ordered_search_ids, with_ids: true)
    ordered_paginated_ids = paginate_array(ordered_ids)

    scope = scope.unscoped.where(id: ordered_paginated_ids)
    # not using `evaluate_scope` because we are already instantiating
    # a scope based on ids
    primary_models = scope.to_a

    # Once hydrated, a page worth of models needs to be reordered
    # due to the `scope.unscoped.where(id: ...` clobbering our ordering
    primary_models = order_for_search(primary_models, ordered_paginated_ids)
  end

  [primary_models, count]
end