Class: Reflective::Search::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/reflective/search.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, &block) ⇒ Index

Returns a new instance of Index.



32
33
34
35
36
# File 'lib/reflective/search.rb', line 32

def initialize(name, &block)
  @name = name
  @indexes = {}
  instance_eval(&block)
end

Instance Method Details

#add(item) ⇒ Object



46
47
48
49
50
51
52
# 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) ⇒ Object



38
39
40
# File 'lib/reflective/search.rb', line 38

def category(name)
  @indexes[name] = Hash.new { Set.new }
end

#clearObject



54
55
56
57
58
# File 'lib/reflective/search.rb', line 54

def clear
  @indexes.each do |name, _|
    @indexes[name] = Hash.new { Set.new }
  end
end

#search(query) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/reflective/search.rb', line 60

def search(query)
  tokenized_query = tokenize(query).to_set
  matches = @indexes.reduce([]) do |acc, (_, index)|
    index.select { |k, _| tokenized_query.include? k }
         .each_value do |found|
      acc += found.to_a
    end
    acc
  end
  to_results(matches)
end

#tokenize(value) ⇒ Object



42
43
44
# File 'lib/reflective/search.rb', line 42

def tokenize(value)
  value&.downcase&.split&.map(&:strip) || []
end