Class: Vivlio::Starter::CLI::Metrics::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/vivlio/starter/cli/metrics/cache.rb

Overview

メトリクスキャッシュを管理する

Constant Summary collapse

CACHE_DIR =
'.cache/metrics'
DISABLE_ENV =
'VIVLIO_METRICS_CACHE'

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir: CACHE_DIR) ⇒ Cache

Returns a new instance of Cache.



36
37
38
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 36

def initialize(cache_dir: CACHE_DIR)
  @cache_dir = cache_dir
end

Instance Method Details

#cache_file_path(basename) ⇒ Object

キャッシュファイルのパスを取得する



96
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 96

def cache_file_path(basename) = File.join(cache_dir, "#{basename}.yml")

#clear!Object

全キャッシュをクリアする



91
92
93
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 91

def clear!
  FileUtils.rm_rf(cache_dir)
end

#enabled?Boolean

キャッシュが有効か判定する

Returns:

  • (Boolean)


41
42
43
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 41

def enabled?
  ENV[DISABLE_ENV] != '0'
end

#ensure_cache_dir!Object

キャッシュディレクトリを初期化する



46
47
48
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 46

def ensure_cache_dir!
  FileUtils.mkdir_p(cache_dir)
end

#fresh?(basename, source_path) ⇒ Boolean

キャッシュが有効(新鮮)か判定する

Returns:

  • (Boolean)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 51

def fresh?(basename, source_path)
  return false unless enabled?
  return false unless source_path

  cache_path = cache_file_path(basename)
  return false unless File.exist?(cache_path)
  return false unless File.exist?(source_path)

  cache_mtime = File.mtime(cache_path)
  source_mtime = File.mtime(source_path)

  cache_mtime >= source_mtime
rescue Errno::ENOENT
  false
end

#read(basename, source_path) ⇒ Object

キャッシュからデータを読み込む



68
69
70
71
72
73
74
75
76
77
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 68

def read(basename, source_path)
  return nil unless fresh?(basename, source_path)

  cache_path = cache_file_path(basename)
  data = YAML.safe_load_file(cache_path, permitted_classes: [Symbol])

  CacheEntry.new(basename:, mtime: File.mtime(cache_path), data:)
rescue Psych::SyntaxError, Errno::ENOENT
  nil
end

#write(basename, data, source_path: nil) ⇒ Object

キャッシュにデータを書き込む



80
81
82
83
84
85
86
87
88
# File 'lib/vivlio/starter/cli/metrics/cache.rb', line 80

def write(basename, data, source_path: nil) # rubocop:disable Lint/UnusedMethodArgument
  return unless enabled?

  ensure_cache_dir!
  cache_path = cache_file_path(basename)
  File.write(cache_path, data.to_yaml)
rescue Errno::EACCES => e
  Common.log_warn("キャッシュ書き込みに失敗: #{e.message}")
end