From 3d9dadd362d81d6ae506d577fbe6f264164bcc46 Mon Sep 17 00:00:00 2001 From: Macartur Sousa Date: Wed, 8 Jun 2016 12:58:47 -0300 Subject: [PATCH] Refactored search controller and view --- plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb | 53 ++++++++++++++++++++++++++++++++++------------------- plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb | 15 +++++++++------ 2 files changed, 43 insertions(+), 25 deletions(-) diff --git a/plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb b/plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb index 820a9dc..39cc674 100644 --- a/plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb +++ b/plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb @@ -21,33 +21,35 @@ class ElasticsearchPluginController < ApplicationController define_searchable_types define_search_fields_types + process_results + end + + def process_results @query = params[:q] - @results = [] if @selected_type == :all - SEARCHABLE_TYPES.keys.each do |type| - results type.to_s - end + @results = search_from_all_models else - results @selected_type + @results = search_from_model @selected_type end end - private - def get_query text, klass + def fields_from_model + klass::SEARCHABLE_FIELDS.map do |key, value| + if value[:weight] + "#{key}^#{value[:weight]}" + else + "#{key}" + end + end + end + + def get_query text, klass=nil query = {} unless text.blank? - fields = klass::SEARCHABLE_FIELDS.map do |key, value| - if value[:weight] - "#{key}^#{value[:weight]}" - else - "#{key}" - end - end - query = { query: { match_all: { @@ -74,14 +76,23 @@ class ElasticsearchPluginController < ApplicationController query end - def results model + + def search_from_all_models + models = [] + query = get_query params[:q] + + SEARCHABLE_TYPES.keys.each {| model | models.append( model.to_s.classify.constantize) if model != :all } + Elasticsearch::Model.search(query, models, size: default_per_page).page(params[:page]).records + end + + def search_from_model model begin klass = model.to_s.classify.constantize + query = get_query params[:q], klass + klass.search(query, size: default_per_page).page(params[:page]).records rescue - return + [] end - query = get_query params[:q], klass - @results |= klass.__elasticsearch__.search(query).records.to_a end def define_searchable_types @@ -94,4 +105,8 @@ class ElasticsearchPluginController < ApplicationController @selected_filter_field = params[:selected_filter_field].nil? ? SEARCH_FILTERS.keys.first : params[:selected_filter_field].to_sym end + def default_per_page + 10 + end + end diff --git a/plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb b/plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb index aa50b66..6c55498 100644 --- a/plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb +++ b/plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb @@ -2,7 +2,7 @@ -- libgit2 0.21.2