Class: LibyearRb::FileCache

Inherits:
Object
  • Object
show all
Defined in:
lib/libyear_rb/file_cache.rb

Constant Summary collapse

CACHE_EXPIRATION =

24 hours in seconds

86_400
CACHE_DIR_ROOT =
ENV.fetch("XDG_CACHE_HOME", File.join(Dir.home, ".cache"))
CACHE_DIR_DEFAULT =
File.join(CACHE_DIR_ROOT, "libyear-rb")
SKIP_CACHE =
ENV.fetch("SKIP_CACHE", "0") == "1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir: CACHE_DIR_DEFAULT, skip_cache: SKIP_CACHE) ⇒ FileCache

Returns a new instance of FileCache.



15
16
17
18
# File 'lib/libyear_rb/file_cache.rb', line 15

def initialize(cache_dir: CACHE_DIR_DEFAULT, skip_cache: SKIP_CACHE)
  @cache_dir = Pathname.new(cache_dir)
  @skip_cache = skip_cache
end

Instance Attribute Details

#cache_dirObject (readonly)

Returns the value of attribute cache_dir.



13
14
15
# File 'lib/libyear_rb/file_cache.rb', line 13

def cache_dir
  @cache_dir
end

Instance Method Details

#fetch(remote_host, gem_name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/libyear_rb/file_cache.rb', line 20

def fetch(remote_host, gem_name)
  return yield if @skip_cache

  path = cache_file_path(remote_host, gem_name)
  if cache_valid?(path)
    JSON.parse(path.read)
  else
    data = yield
    return data if data.empty?

    path.dirname.mkpath
    path.write(JSON.dump(data))
    path.utime(Time.now, Time.now)
    data
  end
end