Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Last active November 21, 2022 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/3e72766516e69203bddc2291bf630622 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/3e72766516e69203bddc2291bf630622 to your computer and use it in GitHub Desktop.
# FeedsCache.set_backend(FeedsCache::FileBackend)
# FeedsCache.fetch('foo', 60) { 'bar' }
# FeedsCache.persist
module FeedsCache
module_function
def set_backend(backend)
@backend = backend
end
def fetch(key, expiration = nil)
set(key, yield, expiration) unless cache[key]
get(key)
end
def get(key, default = nil)
return default unless cache[key]
cache[key]['l'] = Time.now.to_i
cache[key]['v']
end
def set(key, value, expiration = nil)
cache[key] = { 'v' => value, 'l' => Time.now.to_i }
cache[key]['e'] = Time.now.to_i + expiration if expiration
end
def cache
@cache ||= expire_items(@backend.load_cache)
end
def expire_items(cache)
now = Time.now.to_i
lru_expires = now - 30 * 24 * 3600
cache.select do |_, v|
(v['e'] && v['e'] > now) || v['l'] > lru_expires
end
end
def persist
@backend.persist(cache)
end
module S3Backend
module_function
def load_cache
cache_string = S3.client.get_object(
bucket: ENV['BUCKET_NAME'],
key: 'cache/cache.json'
).body.string rescue '{}'
JSON.parse(cache_string) rescue {}
end
def persist(cache)
S3.client.put_object(
acl: 'private',
bucket: ENV['BUCKET_NAME'],
key: 'cache/cache.json',
body: JSON.dump(cache)
)
end
end
module FileBackend
module_function
def load_cache
str = File.read('feeds_cache.json') rescue '{}'
JSON.parse(str)
end
def persist(cache)
File.open('feeds_cache.json', 'w') do |f|
f.puts JSON.dump(cache)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment