开发者

Simple way to cache twitter gem tweet in Sinatra?

开发者 https://www.devze.com 2023-01-30 03:38 出处:网络
I\'m running into API Limit Requests which end up blowing my site up. Right now to avoid that I have the tweet request from the Twitter gem in a rescue block that returns a default string if somethin

I'm running into API Limit Requests which end up blowing my site up.

Right now to avoid that I have the tweet request from the Twitter gem in a rescue block that returns a default string if something bad happens.

I'm wondering what would be the best way to cache the latest tweet simply using:

  @开发者_开发技巧twitter = Twitter.user_timeline("some_user", :include_rts => 1, :count => 1).first

In case the API limit is hit?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消