Class: Decidim::Search

Inherits:
Rectify::Command
  • Object
show all
Defined in:
app/commands/decidim/search.rb

Overview

A command that will act as a search service, with all the business logic for performing searches.

Constant Summary collapse

ACCEPTED_FILTERS =
[:decidim_scope_id].freeze
HIGHLIGHTED_RESULTS_COUNT =
4

Instance Method Summary collapse

Constructor Details

#initialize(term, organization, filters = {}, page_params = {}) ⇒ Search

Public: Initializes the command.

Parameters:

  • term:

    The term to search for.

  • organization:

    The Organization to which the results are constrained.

  • filters: (optional)

    A Hash of SearchableResource attributes to filter for.

  • page_params: (optional)

    A Hash with ‘page` and `per_page` options to paginate.



15
16
17
18
19
20
# File 'app/commands/decidim/search.rb', line 15

def initialize(term, organization, filters = {}, page_params = {})
  @term = term
  @organization = organization
  @filters = filters.with_indifferent_access
  @page_params = page_params
end

Instance Method Details

#callObject

Executes the command. Broadcasts these events:

  • :ok when everything is valid, together with the search results.

  • :invalid if something failed and couldn’t proceed.

Returns nothing.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/commands/decidim/search.rb', line 28

def call
  search_results = Decidim::Searchable.searchable_resources.inject({}) do |results_by_type, (class_name, klass)|
    result_ids = filtered_query_for(class_name).pluck(:resource_id)
    results_count = result_ids.count

    results = if filters[:resource_type].present? && filters[:resource_type] == class_name
                paginate(klass.order_by_id_list(result_ids))
              elsif filters[:resource_type].present?
                ApplicationRecord.none
              else
                klass.order_by_id_list(result_ids.take(HIGHLIGHTED_RESULTS_COUNT))
              end

    results_by_type.update(class_name => {
                             count: results_count,
                             results: results
                           })
  end
  broadcast(:ok, search_results)
end