public
Last active

Twitter Caching

  • Download Gist
Tweet Caching.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
class Tweet < ActiveRecord::Base
def self.fetch_new
# attempt to connect and authenticate to Twitter
httpauth = Twitter::HTTPAuth.new(ENV['TWITTER_USR'], ENV['TWITTER_PWD'])
client = Twitter::Base.new(httpauth)
# fetch a new tweet, cache it to the database, and then return it
Tweet.create :text => client.user_timeline.first.text
client.user_timeline.first.text
rescue Twitter::Unauthorized
'Could not connect to Twitter.'
rescue Twitter::RateLimitExceeded
'Hourly rate limit exceeded.'
end
# return cached tweet unless cache empty or expired else fetch new
def self.latest
cached = Tweet.first
case true
when cached.nil?
Tweet.fetch_new
when cached.created_at < ENV['CACHE_TIMEOUT'].to_i.minute.ago
Tweet.delete_all
Tweet.fetch_new
else
cached.text
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.