-
-
Save leonid-shevtsov/3e72766516e69203bddc2291bf630622 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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