Created
July 6, 2017 01:59
-
-
Save bennacer860/a3d7849ed2599aab6ac7dab8864e48ce 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
class Cache | |
@redis = {} | |
def self.fetch key, expires_in = 30, &block | |
puts "" | |
puts @redis | |
if @redis.key?(key) && (@redis[key][:expiration_time] > Time.now.to_i) | |
# fetch and return result | |
puts "fetch from cache and will expire in #{@redis[key][:expiration_time] - Time.now.to_i}" | |
@redis[key][:value] | |
else | |
if block_given? | |
# make the DB query and create a new entry for the request result | |
puts "did not find key in cache, executing block ..." | |
@redis[key] = {value: yield(block), expiration_time: Time.now.to_i + expires_in} | |
@redis[key][:value] | |
else | |
# no block given, do nothing | |
nil | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment