Class: SKJVS::OneFile

Inherits:
Object
  • Object
show all
Defined in:
lib/skjvs/one_file.rb

Constant Summary collapse

DEFAULT_FILENAME =
"skjvs_store.txt"

Instance Method Summary collapse

Constructor Details

#initialize(path = DEFAULT_FILENAME) ⇒ OneFile

Returns a new instance of OneFile.



7
8
9
10
11
# File 'lib/skjvs/one_file.rb', line 7

def initialize path = DEFAULT_FILENAME
  @path = path
  @cache = {}
  @pos = 0
end

Instance Method Details

#[](key) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/skjvs/one_file.rb', line 13

def [] key
  ::File.open @path, "r" do |file|
    file.flock ::File::LOCK_SH

    # TODO: do not parse values until EOF is reached
    file.seek @pos
    while line = file.gets
      next if line.start_with? " "
      @cache[line[0, 32].freeze] = ::JSON.parse line[33..-2]
    end
    @pos = file.pos

  end if ::File.size(@path) > @pos if ::File.exist?(@path)
  @cache[::Digest::MD5.hexdigest key.to_s]
end

#[]=(key, value) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/skjvs/one_file.rb', line 29

def []= key, value
  ::File.open @path, "a" do |file|
    file.flock ::File::LOCK_EX
    file.puts "#{::Digest::MD5.hexdigest key.to_s} #{::JSON.generate value}"
    file.flush
  end
end