class Reflective::Search::Index

Public Class Methods

new(name, &block) click to toggle source
# File lib/reflective/search.rb, line 32
def initialize(name, &block)
  @name = name
  @indexes = {}
  instance_eval(&block)
end

Public Instance Methods

add(item) click to toggle source
# File lib/reflective/search.rb, line 46
def add(item)
  @indexes.each do |category, index|
    tokenize(item.send(category)).each do |word|
      index[word] = index[word].add item.id
    end
  end
end
category(name) click to toggle source
# File lib/reflective/search.rb, line 38
def category(name)
  @indexes[name] = Hash.new { Set.new }
end
clear() click to toggle source
# File lib/reflective/search.rb, line 54
def clear
  @indexes.each do |name, _|
    @indexes[name] = Hash.new { Set.new }
  end
end
tokenize(value) click to toggle source
# File lib/reflective/search.rb, line 42
def tokenize(value)
  value&.downcase&.split&.map(&:strip) || []
end

Private Instance Methods

to_results(matches) click to toggle source
# File lib/reflective/search.rb, line 74
def to_results(matches)
  Results.new(matches.tally
           .map { |id, count| Result.new(id: id, score: count) }
           .sort { |a, b| b.score <=> a.score })
end