Question

I'm making a basic Sinatra application to display a user's Twitter mentions timeline using the Twitter gem. After logging in, I fetch his/her mentions. Something like:

get '/' do
  @mentions = Twitter.mentions_timeline

  erb :home
end

The issue with this is that I am making a call to the Twitter API every single time the user hits the homepage. I get rate limited and it's also not efficient, since I only want to re-fetch the mentions timeline, say, every 3 minutes. Or if it's simpler, I could just use the cache once I hit the rate limit.

After reading up, it seems like the best way to do this would be store this data in cache so I don't keep making API requests. How would I go about doing that?

Was it helpful?

Solution

I do this by storing the tweets in redis. I am loading the tweets in a helper function, so that I can access the same cached copy in multiple routes.

All my code is on https://github.com/timmillwood/millwoodonline/blob/master/helpers/main.rb#L38 feel free to take what you need.

OTHER TIPS

The obvious way would be to store the user's timeline in a database. Using something like MongoDB is pretty trivial, since the Twitter API returns json and you can just toss the tweets in there as they come. Before calling the Twitter API check the age of the most recent mention of the user, and don't call if it's relatively new (e.g. 30 minutes or less).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top