Class: Fontist::Utils::Cache

Inherits:
Object
  • Object
show all
Includes:
Locking
Defined in:
lib/fontist/utils/cache.rb

Constant Summary collapse

MAX_FILENAME_SIZE =
255

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Locking

#lock

Constructor Details

#initialize(cache_path: nil) ⇒ Cache

Returns a new instance of Cache.



61
62
63
# File 'lib/fontist/utils/cache.rb', line 61

def initialize(cache_path: nil)
  @cache_path = cache_path || Fontist.downloads_path
end

Instance Attribute Details

#cache_pathObject (readonly)

Returns the value of attribute cache_path.



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

def cache_path
  @cache_path
end

Class Method Details

.lock_path(path) ⇒ Object



65
66
67
# File 'lib/fontist/utils/cache.rb', line 65

def self.lock_path(path)
  "#{path}.lock"
end

Instance Method Details

#already_fetched?(keys) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
86
# File 'lib/fontist/utils/cache.rb', line 83

def already_fetched?(keys)
  map = load_cache
  keys.find { |k| cache_exist?(map[k]) }
end

#delete(key) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'lib/fontist/utils/cache.rb', line 88

def delete(key)
  lock(lock_path) do
    map = load_cache
    return unless map[key]

    value = map.delete(key)
    map.to_file(cache_map_path)
    value
  end
end

#fetch(key) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/fontist/utils/cache.rb', line 69

def fetch(key)
  map = load_cache
  if Fontist.use_cache? && cache_exist?(map[key])
    print_cached(map[key])

    return downloaded_file(map[key])
  end

  generated_file = yield
  path = save_cache(generated_file, key)

  downloaded_file(path)
end

#set(key, value) ⇒ Object



99
100
101
102
103
104
105
# File 'lib/fontist/utils/cache.rb', line 99

def set(key, value)
  lock(lock_path) do
    map = load_cache
    map[key] = value
    map.to_file(cache_map_path)
  end
end