Created
June 16, 2012 08:11
-
-
Save donfrancisco/2940467 to your computer and use it in GitHub Desktop.
redis twitter datastore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "httparty" | |
require "redis" | |
require_relative "../models/twitter_status" # some wrapper for a Twitter status | |
class TwitterStream | |
attr_reader :twitter_handle, :tweets | |
attr_reader :cache # a helper to the Redis database | |
attr_reader :cached_response # the actual response from a API call | |
that is put into the cache | |
attr_writer :logger # to decouple Rails.logger from the actual service | |
def initialize(twitter_handle, cache = Redis.public_method(:new)) | |
@twitter_handle = twitter_handle | |
@tweets = [] | |
@logger = nil | |
@count = 2 | |
@cache = cache.call | |
end | |
# called from the background job, it does the actual API call | |
def fetch_stream | |
@cached_response = | |
HTTParty.get("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=#{twitter_handle}&include_entities=true&include_rts=true&count=#{@count}") | |
@logger.info(@cached_response.body) unless @logger.nil? | |
end | |
# since a background job uses its own environment, the response is | |
put to Redis | |
def push_mem | |
cache.set twitter_handle, Marshal.dump(@cached_response) | |
end | |
# this is used in the application to retrieve the response that has | |
been recorded earlier | |
def pop_mem | |
@cached_response = Marshal.load(cache.get twitter_handle) | |
@tweets = [] | |
@cached_response.each do |tweet| | |
@tweets << TwitterStatus.new(tweet) | |
end | |
@tweets | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment