Skip to content

Instantly share code, notes, and snippets.

@hyrious
Last active April 20, 2017 13:04
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 hyrious/c7a6bcc1dd31b4e35dbbb51333ff8665 to your computer and use it in GitHub Desktop.
Save hyrious/c7a6bcc1dd31b4e35dbbb51333ff8665 to your computer and use it in GitHub Desktop.
Easy API Cache
@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