Skip to content

Instantly share code, notes, and snippets.

@joemsak
Created August 24, 2009 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemsak/174283 to your computer and use it in GitHub Desktop.
Save joemsak/174283 to your computer and use it in GitHub Desktop.
class RssReader
require 'timeout'
def self.posts_for(feed_url, length=2, perform_validation=false)
posts = []
retries = 42
begin
Timeout::timeout(5){
begin
open(feed_url) do |rss|
posts = RSS::Parser.parse(rss, perform_validation).items
end
posts.each do |post|
post.title.gsub!(/(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?/ix) { |w| '<a href="' + w + '">' + w + '</a>' }
post.title.gsub!(/@(\w+)/, '<a class="twitter_name" href="http://www.twitter.com/\\1">@\\1</a>')
post.title.gsub!(/#(\w+)/, '<a class="twitter_hashtag" href="http://search.twitter.com/search?q=\\1">#\\1</a>')
end
posts[0..length - 1] if posts.size > length
rescue OpenURI::HTTPError => error
posts << [post.title = 'No posts available', post.pubDate = Time.now]
end
}
rescue Timeout::Error
retries -= 1
if retries > 0
sleep 0.42 and retry
else
posts << [post.title = 'Twitter is not available', post.pubDate = Time.now]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment