Class: Whodunit::Chronicles::Ledgers::FileLedger

Inherits:
Whodunit::Chronicles::Ledger show all
Defined in:
lib/whodunit/chronicles/ledgers/file_ledger.rb,
sig/whodunit/chronicles/ledgers/file_ledger.rbs

Overview

Append-only newline-delimited JSON ledger for simple durable local storage.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Whodunit::Chronicles::Ledger

#ensure_indexes!, #migrate!, #partition_for, #status, #verify

Constructor Details

#initialize(path:) ⇒ FileLedger

Create a file-backed ledger.

Parameters:

  • path (String)

    path to the NDJSON ledger file

  • path: (String)


18
19
20
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 18

def initialize(path:)
  @path = path.to_s
end

Instance Attribute Details

#pathString (readonly)

Returns path to the NDJSON ledger file.

Returns:

  • (String)

    path to the NDJSON ledger file



13
14
15
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 13

def path
  @path
end

Instance Method Details

#append(entry) ⇒ LedgerEntry

Append one entry as one JSON line.

Parameters:

Returns:



36
37
38
39
40
41
42
43
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 36

def append(entry)
  File.open(path, 'ab') do |file|
    file.flock(File::LOCK_EX)
    file.write(JSON.generate(entry.to_h))
    file.write("\n")
  end
  entry
end

#entriesArray<Hash>

Read all entries from the file as hashes.

Returns:

  • (Array<Hash>)

    decoded ledger lines



48
49
50
51
52
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 48

def entries
  return [] unless File.exist?(path)

  File.readlines(path, chomp: true).reject(&:empty?).map { |line| JSON.parse(line) }
end

#prepare!FileLedger

Ensure the parent directory and ledger file exist.

Returns:



25
26
27
28
29
30
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 25

def prepare!
  directory = File.dirname(path)
  FileUtils.mkdir_p(directory) unless directory == '.'
  FileUtils.touch(path)
  self
end