Class: SkillBench::TrendTracker::Persistence

Inherits:
Object
  • Object
show all
Defined in:
lib/skill_bench/trend_tracker/persistence.rb

Overview

Handles history file persistence operations including backup management

Instance Method Summary collapse

Constructor Details

#initialize(history_file) ⇒ Persistence

Returns a new instance of Persistence.

Parameters:

  • history_file (String)

    Path to the history JSON file



12
13
14
# File 'lib/skill_bench/trend_tracker/persistence.rb', line 12

def initialize(history_file)
  @history_file = File.expand_path(history_file)
end

Instance Method Details

#loadArray<Hash>

Loads history from file with corruption recovery

Returns:

  • (Array<Hash>)

    List of historical entries



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/skill_bench/trend_tracker/persistence.rb', line 19

def load
  return [] unless File.exist?(history_file)

  JSON.parse(File.read(history_file), symbolize_names: true)
rescue JSON::ParserError => e
  backup = read_backup
  return backup if backup

  SkillBench::ErrorLogger.log_error(e, "History file #{history_file} corrupted")
  []
end

#write(history) ⇒ Hash

Writes history to file atomically, snapshotting the previous good version into the backup first.

The existing history file (if any) is copied to #{history_file}.bak before the new content is written, so the backup always holds the previous good version rather than a duplicate of the current file. The new content is serialized once and written via a temp-file + rename so the main file is never left partially written. Returns a result hash so callers do not need to rescue SystemCallError.

Parameters:

  • history (Array<Hash>)

    History entries to write

Returns:

  • (Hash)

    { success: true } on success, { success: false, error: { message: '...' } } on failure



43
44
45
46
47
48
49
50
51
52
# File 'lib/skill_bench/trend_tracker/persistence.rb', line 43

def write(history)
  backup_previous_version
  temp_file = "#{history_file}.tmp"
  File.write(temp_file, JSON.pretty_generate(history))
  File.rename(temp_file, history_file)

  { success: true }
rescue SystemCallError => e
  { success: false, error: { message: e.message } }
end