Class: Rfmt::Cache

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

Overview

Cache system for formatted files Uses mtime (modification time) to determine if formatting is needed

Defined Under Namespace

Classes: CacheError

Constant Summary collapse

DEFAULT_CACHE_DIR =
File.expand_path('~/.cache/rfmt').freeze
CACHE_VERSION =
'1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir: DEFAULT_CACHE_DIR) ⇒ Cache

Returns a new instance of Cache.



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

def initialize(cache_dir: DEFAULT_CACHE_DIR)
  @cache_dir = cache_dir
  @cache_data = {}
  ensure_cache_dir
  load_cache
end

Instance Attribute Details

#cache_dirObject (readonly)

Returns the value of attribute cache_dir.



15
16
17
# File 'lib/rfmt/cache.rb', line 15

def cache_dir
  @cache_dir
end

Instance Method Details

#clearObject

Clear all cache data



53
54
55
56
# File 'lib/rfmt/cache.rb', line 53

def clear
  @cache_data = {}
  save
end

#invalidate(file_path) ⇒ Object

Remove cache for specific file



59
60
61
# File 'lib/rfmt/cache.rb', line 59

def invalidate(file_path)
  @cache_data.delete(file_path)
end

#mark_formatted(file_path) ⇒ Object

Mark file as formatted with current mtime



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

def mark_formatted(file_path)
  return unless File.exist?(file_path)

  @cache_data[file_path] = {
    'mtime' => File.mtime(file_path).to_i,
    'formatted_at' => Time.now.to_i,
    'version' => CACHE_VERSION
  }
end

#needs_formatting?(file_path) ⇒ Boolean

Check if file needs formatting Returns true if file mtime has changed or not in cache

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
# File 'lib/rfmt/cache.rb', line 26

def needs_formatting?(file_path)
  return true unless File.exist?(file_path)

  current_mtime = File.mtime(file_path).to_i
  cached_mtime = @cache_data.dig(file_path, 'mtime')

  current_mtime != cached_mtime
end

#pruneObject

Prune old cache entries (files that no longer exist)



73
74
75
76
77
78
79
80
81
# File 'lib/rfmt/cache.rb', line 73

def prune
  before_count = @cache_data.size
  @cache_data.delete_if { |file_path, _| !File.exist?(file_path) }
  after_count = @cache_data.size
  pruned = before_count - after_count

  save if pruned.positive?
  pruned
end

#saveObject

Save cache to disk



47
48
49
50
# File 'lib/rfmt/cache.rb', line 47

def save
  cache_file = File.join(@cache_dir, 'cache.json')
  File.write(cache_file, JSON.pretty_generate(@cache_data))
end

#statsObject

Get cache statistics



64
65
66
67
68
69
70
# File 'lib/rfmt/cache.rb', line 64

def stats
  {
    total_files: @cache_data.size,
    cache_dir: @cache_dir,
    cache_size_bytes: cache_size
  }
end