Class: Polecat::IndexWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/polecat/index_writer.rb

Overview

handles the writing of new documents to the index.

This class is responsible for writing the documents to the index. It takes a path on creation and checks, if it is an empty or a valid index directory.

When the documents are getting written to the filesystem, a ‘index.lock’ file is written as an extra lock. It then writes a new file into the directory, which has all documents.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ IndexWriter

create a new IndexWriter

This creates a new IndexWriter set to the given path.

Parameters:

  • path (String)

    the path to the index directory



17
18
19
20
21
22
23
24
25
26
# File 'lib/polecat/index_writer.rb', line 17

def initialize path
  if !File.directory? path
    raise ArgumentError, 'not a directory'
  elsif File.exists? path + '/index.lock'
    raise IOError, 'index is locked'
  else
    @path = path
    @documents = []
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



11
12
13
# File 'lib/polecat/index_writer.rb', line 11

def path
  @path
end

Instance Method Details

#add(doc) ⇒ Object

add a new document to the writer

This adds a Document to the temporary storage. Call #write to write them to the filesystem.

Parameters:

  • doc (Document)

    the document to store



42
43
44
45
46
47
48
# File 'lib/polecat/index_writer.rb', line 42

def add doc
  if doc.respond_to? :attributes
    @documents << doc
  else
    raise ArgumentError, 'missing method attributes'
  end
end

#countFixnum

returns the count of elements not flushed

This method returns the count of all elements stored in the Writer, but not yet flushed to a file.

Returns:

  • (Fixnum)

    count of files



33
34
35
# File 'lib/polecat/index_writer.rb', line 33

def count
  @documents.count
end

#create_readerObject

creates an index reader with the writers path



69
70
71
# File 'lib/polecat/index_writer.rb', line 69

def create_reader
  Polecat::IndexReader.new @path
end

#writeBoolean

write all documents to the disc

Write all stored documents to the disc and clear the buffer.

Returns:

  • (Boolean)

    true when the write was a success



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/polecat/index_writer.rb', line 54

def write
  return false unless set_lock
  file_name = generate_filename
          
  File.open file_name, 'w' do |file|
    file.write Marshal.dump(@documents)
  end

  @documents = []
  release_lock
end