module Administrate
  class Search
    def initialize(resolver, term)
      @resolver = resolver
      @term = term
    end

    def run
      if @term.blank?
        resource_class.all
      else
        resource_class.where(query, *search_terms)
      end
    end

    private

    delegate :resource_class, to: :resolver

    def query
      search_attributes.map { |attr| "lower(#{attr}) LIKE ?" }.join(" OR ")
    end

    def search_terms
      ["%#{term.downcase}%"] * search_attributes.count
    end

    def search_attributes
      resolver.dashboard_class::ATTRIBUTE_TYPES.select do |_, type|
        type.searchable?
      end.keys
    end

    attr_reader :resolver, :term
  end
end

module Administrate
  class Search
    def initialize(resolver, term)
      @resolver = resolver
      @term = term
    end

    def run
      if @term.blank?
        resource_class.all
      else
        resource_class.where(query, *search_terms)
      end
    end

    private

    delegate :resource_class, to: :resolver

    def query
      search_attributes.map { |attr| "lower(#{attr}) LIKE ?" }.join(" OR ")
    end

    def search_terms
      ["%#{term.downcase}%"] * search_attributes.count
    end

    def search_attributes
      attribute_types.keys.select do |attribute|
        attribute_types[attribute].searchable?
      end
    end

    def attribute_types
      resolver.dashboard_class::ATTRIBUTE_TYPES
    end

    attr_reader :resolver, :term
  end
end

Speed up selective key fetches from hashes
[OPTIM] Speed up selective key fetches from hashes

Pull Request #293

Problem:

The `ATTRIBUTES_TYPES` hash is being iterated over twice
to determine which values are searchable.

This is an inefficient method
for selecting searchable keys from the hash.

Solution:

Refactor the algorithm
to reduce the time needed to iterate through the hash.

Benchmarks show that the new version is a 22% speedup
from the original.

Several other methods were tried,
as outlined in [this benchmarking script][bench].
Two options gave better than 22% speedup,
but were rejected because they reduced the readability of the code.

[bench]: https://gist.github.com/graysonwright/90017f7d74f19e80b789
