Simple way to cache twitter gem tweet in Sinatra?

a 夏天 提交于 2019-12-08 08:35:22

I use memcache (or now dalli) for stuff like that. There are two options. You could hit the cache first and if the timestamp is within a certain threshold, just return the cached value without incurring an API hit. Or you could use the API, cache the value, and in your rescue block return the cached value if you exceed the API threshold.

require "memcache"
cache = MemCache.new...
...
@twitter = cache.get("some_user").first
if @twitter.nil?
  begin
    @twitter = Twitter.user_timeline... 
    cache.set("some_user", @twitter) if @twitter
  rescue ...
    @twitter = default
  end
end

or

require "memcache"
cache = MemCache.new...
...
begin
  @twitter = Twitter.user_timeline...
  cache.set("some_user", @twitter) if @twitter
rescue...
  @twitter = cache.get("some_user").first||default
end

Then of course you'll need to be running the memcached daemon on the server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!