Skip to content

Instantly share code, notes, and snippets.

@djones
Created September 30, 2010 23:15
Show Gist options
  • Save djones/605486 to your computer and use it in GitHub Desktop.
Save djones/605486 to your computer and use it in GitHub Desktop.
Shows you how to get the latest tweets from RSS, cache them and display them in Refinery CMS
<%
twitter_cache_expiry_maximum = RefinerySetting.find_or_set(:twitter_cache_expiry_seconds, 90)
twitter_cache = RefinerySetting.find_or_set(:twitter_cache, {
:timestamp => Time.now + twitter_cache_expiry_maximum.seconds + 30.seconds
}) # set an invalid one if it doesn't exist.
#cache twitter for 1 minute
unless twitter_cache.nil? or
((Time.now - twitter_cache[:timestamp]) >= twitter_cache_expiry_maximum.to_i)
tweets = twitter_cache[:tweets]
twitter_cache.inspect
end
-%>
<div id='twitter_content'>
<% if tweets.present? %>
<%= render :partial => "/shared/twitter_tweets",
:locals => {:tweets => tweets} %>
<% else %>
<%= image_tag "ajax-loader.gif", :alt => "", :theme => true %> Loading...
<% end %>
</div>
<ul id='tweets'>
<% tweets.each do |tweet| %>
<li>
<%= tweet[:title].gsub("refinerycms: ", "").gsub(/(http:\/\/.*\ ?)/) {
link_to($1, $1, :target => "_blank")
} %>
</li>
<% end if tweets.present? and tweets.any? %>
</ul>
<h2>Latest Tweet</h2>
<%= render :partial => "/shared/latest_tweets" %>
<% content_for :scripts do %>
<script type='text/javascript'>
$(document).ready(function() {
try {
if ($('#twitter_content').children('ul').length == 0) {
$.get("<%= twitter_url %>", function(data, responseText) {
$('#twitter_content').html(data);
});
}
}
catch(error) {
$('#twitter_content').html("Could not load tweets. Click <a href='http://twitter.com/RefineryCMS' target='_blank'>here</a> to see our twitter feed.")
}
});
</scripts>
<% end %>
ActionController::Routing::Routes.draw do |map|
map.twitter '/twitter', :controller => "twitter", :action => "twitter"
end
class TwitterController < ApplicationController
around_filter :cache_twitter, :only => [:twitter]
def twitter
begin
Timeout::timeout(5) {
result = RSSParser.run(RefinerySetting.find_or_set(:twitter_rss_feed_url,
"http://twitter.com/statuses/user_timeline/19258840.rss"))
@tweets = result[:items][0..0] if result.present? and result[:items].present?
}
rescue Timeout::Error => e
logger.warn("timeout exceeded for downloading twitter RSS: #{e}")
@tweets = nil
end
render :partial => "/shared/twitter_tweets",
:locals => {:tweets => @tweets},
:layout => false
end
protected
def cache_twitter
yield
RefinerySetting[:twitter_cache] = {
:tweets => @tweets,
:timestamp => Time.now
} if @tweets.present?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment