Class: Melisa::Search

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/melisa/search.rb

Instance Method Summary collapse

Constructor Details

#initialize(trie, prefix) ⇒ Search

Returns a new instance of Search.



5
6
7
8
# File 'lib/melisa/search.rb', line 5

def initialize(trie, prefix)
  @trie = trie
  @prefix = prefix
end

Instance Method Details

#each(&block) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/melisa/search.rb', line 20

def each(&block)
  reset_agent
  if block_given?
    # Yield each string in alphabetical order
    yield @agent.key_str while @trie.trie.predictive_search(@agent)
  else
    to_enum(&block)
  end
end

#has_keys?Boolean

Returns:

  • (Boolean)


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

def has_keys?
  reset_agent
  return @trie.trie.predictive_search(@agent)
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
49
50
# File 'lib/melisa/search.rb', line 46

def include?(key)
  a = Marisa::Agent.new
  a.set_query(key)
  @trie.trie.lookup(a)
end

#keysObject



34
35
36
37
38
39
# File 'lib/melisa/search.rb', line 34

def keys
  @keys ||= [].tap do |arr|
    reset_agent
    arr << @agent.key_str while @trie.trie.predictive_search(@agent)
  end
end

#reset_agentObject



14
15
16
17
18
# File 'lib/melisa/search.rb', line 14

def reset_agent
  # Reset the agent state so predictive_search iterates through all keys
  @agent = Marisa::Agent.new
  @agent.set_query(@prefix)
end

#search(prefix) ⇒ Object



10
11
12
# File 'lib/melisa/search.rb', line 10

def search(prefix)
  Search.new(@trie, @prefix + prefix)
end

#sizeObject



30
31
32
# File 'lib/melisa/search.rb', line 30

def size
  keys.size
end

#with_prefixes(&block) ⇒ Object



52
53
54
55
56
57
# File 'lib/melisa/search.rb', line 52

def with_prefixes(&block)
  reset_agent
  while @trie.trie.common_prefix_search(@agent)
    block.call(@agent.key_str)
  end
end