Improved caching.
This commit is contained in:
parent
43d99d266e
commit
d3b5cf7586
2 changed files with 29 additions and 26 deletions
|
@ -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
|
||||
|
|
48
lib/rss.rb
48
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
|
Loading…
Reference in a new issue