Class: Whodunit::Chronicles::Ledgers::FileLedger
- Inherits:
-
Whodunit::Chronicles::Ledger
- Object
- Whodunit::Chronicles::Ledger
- Whodunit::Chronicles::Ledgers::FileLedger
- 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
-
#path ⇒ String
readonly
Path to the NDJSON ledger file.
Instance Method Summary collapse
-
#append(entry) ⇒ LedgerEntry
Append one entry as one JSON line.
-
#entries ⇒ Array<Hash>
Read all entries from the file as hashes.
-
#initialize(path:) ⇒ FileLedger
constructor
Create a file-backed ledger.
-
#prepare! ⇒ FileLedger
Ensure the parent directory and ledger file exist.
Methods inherited from Whodunit::Chronicles::Ledger
#ensure_indexes!, #migrate!, #partition_for, #status, #verify
Constructor Details
#initialize(path:) ⇒ FileLedger
Create a file-backed ledger.
18 19 20 |
# File 'lib/whodunit/chronicles/ledgers/file_ledger.rb', line 18 def initialize(path:) @path = path.to_s end |
Instance Attribute Details
#path ⇒ String (readonly)
Returns 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.
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 |
#entries ⇒ Array<Hash>
Read all entries from the file as hashes.
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.
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 |