Last active
April 20, 2017 13:04
-
-
Save hyrious/c7a6bcc1dd31b4e35dbbb51333ff8665 to your computer and use it in GitHub Desktop.
Easy API Cache
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
@api_cache = {} | |
def api_cache id:, threshold:, due:, &blk | |
@api_cache[id] ||= { cache: {} } | |
due_time = case due | |
when Numeric then Time.now + due | |
when Time then due | |
end | |
proc do |*args| # args is the key | |
@api_cache[id][:cache].delete_if { |_key, item| item[:due] < Time.now } | |
unless @api_cache[id][:cache][args] | |
if threshold > @api_cache[id][:cache].size | |
@api_cache[id][:cache][args] = { due: due_time, data: blk[*args] } | |
else | |
next 'Sorry but we\'ve touched the limit.' | |
end | |
end | |
@api_cache[id][:cache][args][:data] | |
end | |
end | |
=begin | |
# 汇率转换 | |
require 'json' | |
require 'net/http' | |
@exchache = | |
api_cache id: 'exchange', threshold: 42, due: 86400 do |from| | |
Net::HTTP.get(URI "http://api.fixer.io/latest?base=#{from}") | |
end | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment