Sha256: 45901248e6d4510dbd9957192dec46bd467a4eb7615896a83ffe7f7193b753e7

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

module Decidim
  # A command that will act as a search service, with all the business logic for performing searches.
  class Search < Rectify::Command
    ACCEPTED_FILTERS = [:resource_type, :decidim_scope_id].freeze

    attr_reader :term, :results

    # Public: Initializes the command.
    #
    # @param term: The term to search for.
    def initialize(term, organization, filters = {})
      @term = term
      @organization = organization
      @filters = filters
    end

    # 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.
    def call
      query = SearchableResource.where(organization: @organization, locale: I18n.locale)
      @filters.each_pair do |attribute_name, value|
        query = query.where(attribute_name => value) if permit_filter?(attribute_name, value)
      end
      @results = if term.present?
                   query.global_search(I18n.transliterate(term))
                 else
                   query.all
                 end

      broadcast(:ok, @results.order("datetime DESC"))
    end

    private

    def permit_filter?(attribute_name, value)
      ACCEPTED_FILTERS.include?(attribute_name.to_sym) && value.present?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
decidim-core-0.12.0.pre app/commands/decidim/search.rb