From d3b5cf75862b79ce2fb293388f1ee801f0e625dd Mon Sep 17 00:00:00 2001 From: Martin Edenhofer Date: Sun, 29 Jul 2012 17:34:30 +0200 Subject: [PATCH] Improved caching. --- lib/cache.rb | 7 +++++-- lib/rss.rb | 48 ++++++++++++++++++++++++------------------------ 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/lib/cache.rb b/lib/cache.rb index 3955b3e2d..ed644ec09 100644 --- a/lib/cache.rb +++ b/lib/cache.rb @@ -3,9 +3,12 @@ module Cache puts 'Cache.delete' + key.to_s Rails.cache.delete( key.to_s ) end - def self.write( key, data ) + def self.write( key, data, params = {} ) + if !params[:expires_in] + params[:expires_in] = 48.hours + end puts 'Cache.write: ' + key.to_s - Rails.cache.write( key.to_s, data ) + Rails.cache.write( key.to_s, data, params) end def self.get( key ) puts 'Cache.get: ' + key.to_s diff --git a/lib/rss.rb b/lib/rss.rb index ac9f2c823..a82f0e4de 100644 --- a/lib/rss.rb +++ b/lib/rss.rb @@ -1,31 +1,31 @@ module RSS def self.fetch(url, limit = 10) cache_key = 'rss::' + url - items = Rails.cache.read( cache_key ) - if !items - puts 'fetch rss...' - response = Net::HTTP.get_response( URI.parse(url) ) - if response.code.to_s != '200' - return - end - rss = SimpleRSS.parse response.body - items = [] - fetched = 0 - rss.items.each { |item| - record = { - :id => item.id, - :title => item.title, - :summary => item.summary, - :link => item.link, - :published => item.published - } - items.push record - fetched += 1 - break item if fetched == limit.to_i - } - Rails.cache.write( cache_key, items, :expires_in => 4.hours ) + items = Cache.get( cache_key ) + return items if items + + puts 'fetch rss...' + response = Net::HTTP.get_response( URI.parse(url) ) + if response.code.to_s != '200' + return end - + rss = SimpleRSS.parse response.body + items = [] + fetched = 0 + rss.items.each { |item| + record = { + :id => item.id, + :title => item.title, + :summary => item.summary, + :link => item.link, + :published => item.published + } + items.push record + fetched += 1 + break item if fetched == limit.to_i + } + Cache.write( cache_key, items, :expires_in => 4.hours ) + return items end end \ No newline at end of file