Created
November 29, 2016 16:33
-
-
Save ssaunier/3f2998eda5919c497754a463ff72beb6 to your computer and use it in GitHub Desktop.
A simple redis-backed cache to put in your `app/services` Rails app.
This file contains hidden or 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
module Cache | |
def from_cache(*args, &block) | |
return yield(self) if ENV['DISABLE_CACHE'] == 'true' | |
expire = default_expire | |
if args.last.is_a?(Hash) | |
options = args.pop | |
expire = options.fetch(:expire, expire) | |
end | |
the_key = key(*args) | |
if (value = redis.get(the_key)).nil? | |
value = yield(self) | |
redis.set(the_key, Marshal.dump(value)) | |
redis.expire(the_key, expire) | |
value | |
else | |
Marshal.load(value) | |
end | |
end | |
def del_all | |
keys = redis.keys("#{self.class.to_s.underscore}:*") | |
redis.del(keys) unless keys.empty? | |
end | |
private | |
def key(*args) | |
"#{self.class.to_s.underscore}:#{args.join(":")}" | |
end | |
def redis | |
$redis | |
end | |
def default_expire | |
1.week | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment