Class: Hedra::Cache
- Inherits:
-
Object
- Object
- Hedra::Cache
- Defined in:
- lib/hedra/cache.rb
Overview
Simple file-based cache for HTTP responses
Constant Summary collapse
- DEFAULT_TTL =
1 hour
3600- MAX_CACHE_SIZE =
Maximum number of cache files
1000
Instance Method Summary collapse
- #clear ⇒ Object
- #clear_expired ⇒ Object
- #get(key) ⇒ Object
-
#initialize(cache_dir: nil, ttl: DEFAULT_TTL, verbose: false) ⇒ Cache
constructor
A new instance of Cache.
- #set(key, value) ⇒ Object
Constructor Details
#initialize(cache_dir: nil, ttl: DEFAULT_TTL, verbose: false) ⇒ Cache
Returns a new instance of Cache.
13 14 15 16 17 18 19 |
# File 'lib/hedra/cache.rb', line 13 def initialize(cache_dir: nil, ttl: DEFAULT_TTL, verbose: false) @cache_dir = cache_dir || File.join(Config::CONFIG_DIR, 'cache') @ttl = ttl @verbose = verbose FileUtils.mkdir_p(@cache_dir) cleanup_if_needed end |
Instance Method Details
#clear ⇒ Object
58 59 60 61 |
# File 'lib/hedra/cache.rb', line 58 def clear FileUtils.rm_rf(@cache_dir) FileUtils.mkdir_p(@cache_dir) end |
#clear_expired ⇒ Object
63 64 65 66 67 68 69 70 |
# File 'lib/hedra/cache.rb', line 63 def clear_expired Dir.glob(File.join(@cache_dir, '*')).each do |file| data = JSON.parse(File.read(file)) File.delete(file) if expired?(data['timestamp']) rescue StandardError # Skip invalid cache files end end |
#get(key) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/hedra/cache.rb', line 21 def get(key) cache_file = cache_path(key) return nil unless File.exist?(cache_file) data = JSON.parse(File.read(cache_file)) if expired?(data['timestamp']) File.delete(cache_file) # Clean up expired file immediately return nil end data['value'] rescue JSON::ParserError # Corrupted cache file, delete it File.delete(cache_file) if File.exist?(cache_file) nil rescue StandardError => e warn "Cache read error: #{e.}" if @verbose nil end |
#set(key, value) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/hedra/cache.rb', line 42 def set(key, value) cache_file = cache_path(key) data = { 'timestamp' => Time.now.to_i, 'value' => value } # Atomic write to prevent corruption temp_file = "#{cache_file}.tmp" File.write(temp_file, JSON.generate(data)) File.rename(temp_file, cache_file) rescue StandardError => e warn "Cache write error: #{e.}" if @verbose File.delete(temp_file) if File.exist?(temp_file) end |