Class: Briskly::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/briskly/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Store

Returns a new instance of Store.



9
10
11
12
# File 'lib/briskly/store.rb', line 9

def initialize(key)
  @key      = key
  @store    = Trie.new
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



7
8
9
# File 'lib/briskly/store.rb', line 7

def key
  @key
end

Instance Method Details

#search(keyword, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/briskly/store.rb', line 43

def search(keyword, options = {})
  keyword = Briskly::Keyword.new(keyword)

  result  = @store.children_with_values(keyword.normalised)
                  .map(&:last)
                  .flatten(1)
                  .sort{ |a, b| a[1] <=> b[1] }

  
  limit   = options.fetch(:limit, result.length)
  counter = 0
  output  = []
  related = []


  # If n elements have the same index that
  # means they are related. Trie will give
  # the best keyword match on it's first
  # position so we should ignore the others
  #
  # `related` keeps the list of related keywords
  result.each do |element|
    next if related[element[1]] 
    related[element[1]] = true

    output << element[0]

    counter += 1
    break if counter == limit
  end
  
  output
end

#with(values) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/briskly/store.rb', line 14

def with(values)
  @store    = Trie.new
  elements = {}

  values.each_with_index do |value, index|

    keywords = Array.new(1) { value[:keyword] }.flatten(1)

    keywords.each do |keyword|
      alternatives = keywords - [ keyword ]
      element      = Briskly::Element.new(keyword, value[:data], alternatives)
      normalised   = element.keyword(:internal).normalised

      # We need to make sure we keep the index
      # and in order to avoid loops always order
      # the array after each insertion
      elements[normalised] ||= []
      elements[normalised].push([element, index])
                           .sort! { |a,b| a[1] <=> b[1] }
    end

  end


  elements.each do |key, values|
    @store.add key, values
  end
end