Sha256: 74785b983970d2e3cd17c0e50cec357c10e249fe86988250707ca2c4190250d1

Contents?: true

Size: 1.79 KB

Versions: 6

Compression:

Stored size: 1.79 KB

Contents

module ExpressAdmin
  class Search
    def self.execute(scope, params = nil)
      @search_results = []
      @tables_traversed = []
      @scope = scope
      @params = params
      self.search_parent_tables(scope)
      @search_results = @search_results | scope.basic_search(params) if scope.columns.map(&:type).include? :string
      @search_results = @search_results | scope.fuzzy_search(params) if scope.columns.map(&:type).include? :string
      @search_results
    end

    def self.search_parent_tables(scope)
      @associations = scope.reflect_on_all_associations(:belongs_to).map(&:name)
      if @associations.present?
        @associations.each do |assoc|
          @tables_traversed.push assoc
          associated_table = scope.reflect_on_association(assoc.to_sym).try(:klass) rescue nil
          unless associated_table.nil?
            column_names = self.get_columns(associated_table).map(&:name)
            column_names.each do |columns|
              # Search using Textacular
              result = @scope.joins(self.join_generator).fuzzy_search(associated_table.table_name.to_sym =>
                                                                 {columns.to_sym => @params })
              @search_results = @search_results | result unless result.empty?
            end
            self.search_parent_tables(associated_table)
          end
        end
      end
      @tables_traversed.pop
    end

    def self.join_generator
      @tables_traversed.reverse.inject { |memo, table| {table => memo} }
    end

    def self.get_columns(associated_table)
      assoc_table_columns = associated_table.columns
      string_columns = []
      assoc_table_columns.each do |columns|
        if columns.type.eql? :string
          string_columns << columns
        end
      end
      string_columns
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
express_admin-1.7.12 lib/express_admin/search.rb
express_admin-1.7.11 lib/express_admin/search.rb
express_admin-1.7.10 lib/express_admin/search.rb
express_admin-1.7.9 lib/express_admin/search.rb
express_admin-1.7.8 lib/express_admin/search.rb
express_admin-1.7.7 lib/express_admin/search.rb