Class: SortIndex::File

Inherits:
File
  • Object
show all
Defined in:
lib/sort_index/file.rb

Instance Method Summary collapse

Instance Method Details

#sorted_puts(line) ⇒ Nil

adds the line to the while maintaining the data’s sort order

Parameters:

  • line (String)

    to add to the file, it should not have it’s own line ending.

Returns:

  • (Nil)

    always returns nil to match standard #puts method



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sort_index/file.rb', line 8

def sorted_puts(line)
  if line == nil || line.size == 0
    raise ArgumentError, 'Line cannot be blank!'
  end
  if line.index($/)
    raise ArgumentError, "Cannot `puts` a line with extra line endings. Make sure the line does not contain `#{$/.inspect}`"
  end

  matched, idx = binary_seek(line)

  if matched
    # an exact match was found, nothing to do
  else
    if idx == nil
      # append to end of file
      self.seek(0, IO::SEEK_END)
      puts(line)
    else
      self.seek(cached_positions[idx][0], IO::SEEK_SET)
      do_at_current_position{puts(line)}
    end
    update_cached_position(idx, line)
  end
  nil
end