Skip to content
Snippets Groups Projects
learning_object.rb 1.47 KiB
Newer Older
module SearchService
  class LearningObject < Model
    def search
      ::LearningObject.search(@search.query, where: where_hash, order: order_hash, page: @search.page, per_page: @search.results_per_page)
    end

    def autocomplete
      params = {  where: { state: validate_object },
                  fields: ['name^10', 'description', 'author'] }
      result = ::LearningObject.search(@search.query, autocomplete_params.merge(params))

      thumbnail = proc { |obj| obj.default_thumbnail }
      type = proc { |obj| obj.object_type.try(:name) }
      autocomplete_render(result, type, thumbnail)
    end

    private

    def where_hash
      hash = {}
      hash[:tags] = @search.tags unless @search.tags.blank?
      hash[:object_type] = @search.types unless @search.types.blank?
      hash[:state] = validate_object
      hash.blank? ? nil : hash
    end

    def order_hash
      case @search.order
      when 'author' then { author: { order: :asc, unmapped_type: :string } }
      when 'publicationasc' then { published_at: { order: :asc, unmapped_type: :timestamp } }
      when 'publicationdesc' then { published_at: { order: :desc, unmapped_type: :timestamp } }
      when 'title' then { name: { order: :asc, unmapped_type: :string } }
      else { score: { order: :desc, unmapped_type: :integer } }
      end
    end

    def validate_object
      return ::LearningObject.states[:published] unless !@user.nil? && @user.is_admin?
      ::LearningObject.states.values