Class: I18nContextGenerator::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/i18n_context_generator/cache.rb

Overview

File-based cache for LLM results, keyed by translation key and source context.

Constant Summary collapse

DEFAULT_DIR =
'.i18n-context-generator-cache'
CACHE_DIR =

Backward-compatible constant name.

DEFAULT_DIR
CACHE_VERSION =

Bump this when prompt format, search heuristics, or output schema change

'v5'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enabled: true, directory: DEFAULT_DIR) ⇒ Cache

Returns a new instance of Cache.



18
19
20
21
22
# File 'lib/i18n_context_generator/cache.rb', line 18

def initialize(enabled: true, directory: DEFAULT_DIR)
  @enabled = enabled
  @directory = directory
  FileUtils.mkdir_p(@directory) if @enabled && !File.directory?(@directory)
end

Instance Attribute Details

#directoryObject (readonly)

Returns the value of attribute directory.



16
17
18
# File 'lib/i18n_context_generator/cache.rb', line 16

def directory
  @directory
end

Instance Method Details

#clearObject



46
47
48
49
50
51
52
53
# File 'lib/i18n_context_generator/cache.rb', line 46

def clear
  return unless File.directory?(@directory)

  Dir.children(@directory).grep(/\A(?:[a-f0-9]{32}(?:[a-f0-9]{32})?\.json|context-cache-.*\.tmp)\z/).each do |filename|
    FileUtils.rm_f(File.join(@directory, filename))
  end
  Dir.rmdir(@directory) if safe_to_remove_empty_directory? && Dir.empty?(@directory)
end

#get(key, text, context: nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/i18n_context_generator/cache.rb', line 24

def get(key, text, context: nil)
  return nil unless @enabled

  path = cache_path(key, text, context)
  return nil unless File.exist?(path)

  Oj.load_file(path, symbol_keys: true)
rescue StandardError => e
  warn "Cache read error for #{key}: #{e.message}"
  nil
end

#set(key, text, result, context: nil) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/i18n_context_generator/cache.rb', line 36

def set(key, text, result, context: nil)
  return unless @enabled
  return if result[:error] || result['error']

  path = cache_path(key, text, context)
  write_atomically(path, Oj.dump(result, indent: 2, mode: :compat))
rescue StandardError => e
  warn "Cache write error for #{key}: #{e.message}"
end