Created
February 5, 2010 19:13
-
-
Save vapidbabble/296105 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'rss/2.0' | |
require 'open-uri' | |
module ApplicationHelper | |
class EmptyURL < RuntimeError | |
end | |
def rss_content(name) | |
content_object = StaticContent.find_by_name(name) | |
if content_object.nil? || (Time.now - content_object.updated_at) > 4.hours | |
url_object = StaticContent.find_by_name("#{name}_url") | |
raise EmptyURL if url_object.nil? | |
rss_array = read_rss_feed_into_array(url_object.content) | |
# render_content_from_rss_array should be defined in the helper pertaining | |
# to whatever controller is calling cached_rss_content | |
content = render_content_from_rss_array(rss_array) | |
# must update :updated_at because if the content is the same as what is | |
# already in the databased, then the database row is not updated, and we | |
# would keep checking the URL until the blog contents were changed (ie: | |
# caching would only work for the first 4 hours after the blog were updated) | |
attributes = { :name => name, :content => content, :updated_at => Time.now } | |
if content_object.nil? : StaticContent.create(attributes) | |
else content_object.update_attributes(attributes) | |
end | |
else | |
content = content_object.content | |
end | |
content | |
rescue SocketError, EmptyURL, RSS::Error | |
if content_object.nil? | |
'' | |
else | |
# something is wrong, update the cache so we don't check every time this | |
# is viewed | |
content_object.update_attributes(:updated_at => Time.now) | |
content_object.content | |
end | |
end | |
private | |
def read_rss_feed_into_array(feed_url) | |
rss_array = [] | |
open(feed_url) do |http| | |
result = RSS::Parser.parse(http.read, false) | |
return [] if result.nil? | |
i = 0 | |
result.items.each do |item| | |
rss_array << { :title => item.title, | |
:url => item.link, | |
:date => item.date, | |
:content => item.description } | |
i += 1 | |
break if i > 4 | |
end | |
end | |
rss_array | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment