Class: Decidim::Search

Inherits:
Command show all
Defined in:
decidim-core/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_eq].freeze
HIGHLIGHTED_RESULTS_COUNT =
4

Instance Method Summary collapse

Methods inherited from Command

call, #evaluate, #method_missing, #respond_to_missing?, #transaction, #with_events

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 'decidim-core/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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Decidim::Command

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 could not proceed.

Returns nothing.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'decidim-core/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[:with_resource_type].present? && filters[:with_resource_type] == class_name
                paginate(klass.order_by_id_list(result_ids))
              elsif filters[:with_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:
                           })
  end
  broadcast(:ok, search_results)
end