Skip to content

Instantly share code, notes, and snippets.

@timnovinger
Created April 22, 2010 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save timnovinger/375489 to your computer and use it in GitHub Desktop.
Save timnovinger/375489 to your computer and use it in GitHub Desktop.
Twitter Caching
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment