Class: Decidim::Search

Inherits:
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

HIGHLIGHTED_RESULTS_COUNT =
4

Instance Method Summary collapse

Constructor Details

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

Public: Initializes the command.

Parameters:

  • term (String)
    • The term to search for.
  • organization (Decidim::Organization)
    • The Organization to which the results are constrained.
  • filters (Hash) (defaults to: {})
    • (optional) A Hash of SearchableResource attributes to filter for.
  • page_params (Hash) (defaults to: {})
    • (optional) A Hash with page and per_page options to paginate.


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

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

Returns nothing.



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
# File 'app/commands/decidim/search.rb', line 27

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

    uncommentable_resources = uncommentable_resources(results) if results.present?
    if uncommentable_resources.present?
      results -= uncommentable_resources
      results_count -= uncommentable_resources.count
    end

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