From 75f026b1823af8b0556cf5f14e8d374a6f7b8074 Mon Sep 17 00:00:00 2001 From: joshua stein Date: Tue, 10 Jul 2012 14:43:51 -0500 Subject: [PATCH] do some short caching for guest views of story indexes --- app/controllers/home_controller.rb | 45 ++++++++++++++++++++++++------ config/application.rb | 4 ++- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 9a6dc0a..15a7713 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -53,6 +53,27 @@ class HomeController < ApplicationController private def find_stories_for_user_and_tag_and_newest(user, tag = nil, newest = false) + @page = 1 + if params[:page].to_i > 0 + @page = params[:page].to_i + end + + # guest views have caching, but don't bother for logged-in users + if user + stories, @show_more = _find_stories_for_user_and_tag_and_newest(user, + tag, newest) + else + stories, @show_more = Rails.cache.fetch("stories tag:" << + "#{tag ? tag.tag : ""} new:#{newest} page:#{@page.to_i}", + :expires_in => 45) do + _find_stories_for_user_and_tag_and_newest(user, tag, newest) + end + end + + stories + end + + def _find_stories_for_user_and_tag_and_newest(user, tag = nil, newest = false) conds = [ "is_expired = 0 AND is_moderated = 0 " ] if user && !newest @@ -72,11 +93,6 @@ private conds.push @user.id end - @page = 1 - if params[:page].to_i > 0 - @page = params[:page].to_i - end - stories = Story.find( :all, :conditions => conds, @@ -86,10 +102,10 @@ private :order => (newest ? "stories.created_at DESC" : "hotness") ) - @show_more = false + show_more = false if stories.count > STORIES_PER_PAGE - @show_more = true + show_more = true stories.pop end @@ -107,6 +123,19 @@ private end end - stories + # eager load comment counts + if stories.any? + comment_counts = {} + Keystore.find(:all, :conditions => stories.map{|s| + "`key` = 'story:#{s.id}:comment_count'" }.join(" OR ")).each do |ks| + comment_counts[ks.key[/\d+/].to_i] = ks.value + end + + stories.each do |s| + s._comment_count = comment_counts[s.id].to_i + end + end + + [ stories, show_more ] end end diff --git a/config/application.rb b/config/application.rb index 7298b6d..bffcf0f 100644 --- a/config/application.rb +++ b/config/application.rb @@ -48,13 +48,15 @@ module Lobsters # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. - # config.active_record.whitelist_attributes = true + config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' + + config.cache_store = :memory_store end end