Class: PrettySearch::MemoryCollection

Inherits:
Collection
  • Object
show all
Defined in:
lib/pretty_search/collection/memory_collection.rb

Overview

PrettySearch::MemoryCollection parses the given data_file into hash and keep everything in memory, and iterates through the records naively from beginning to end when searching

Instance Method Summary collapse

Methods inherited from Collection

load

Constructor Details

#initialize(data_file, first: false) ⇒ MemoryCollection

Returns a new instance of MemoryCollection.



7
8
9
10
# File 'lib/pretty_search/collection/memory_collection.rb', line 7

def initialize(data_file, first: false)
  @data_file = data_file
  @first = first
end

Instance Method Details

#search(query) ⇒ Array<PrettySearch::Document>

Returns:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/pretty_search/collection/memory_collection.rb', line 13

def search(query)
  data = Yajl::Parser.parse(File.new(@data_file))
  if @first
    found = data.detect { |doc| query.match(doc) }
    if found
      Array(PrettySearch::Document.new(found))
    else
      []
    end
  else
    data.select { |doc| query.match(doc) }
        .map { |doc| PrettySearch::Document.new doc }
  end
end