diff app/controllers/pastes_controller.rb @ 320:612bc7c32324

Use memcached for caching.
author edogawaconan <me@myconan.net>
date Sun, 06 Apr 2014 03:04:43 +0900
parents 61f7f258a6fb
children fec39456dcbe
line wrap: on
line diff
--- a/app/controllers/pastes_controller.rb	Sun Apr 06 01:23:15 2014 +0900
+++ b/app/controllers/pastes_controller.rb	Sun Apr 06 03:04:43 2014 +0900
@@ -1,5 +1,5 @@
 class PastesController < ApplicationController
-  caches_page :show
+  before_action :lowercase_path, :only => :show
 
   # GET /1
   # GET /1.txt
@@ -7,10 +7,9 @@
     @paste = Paste.safe_find(params[:id])
     head :not_found and return unless @paste
 
-    expires_in 1.year, :public => true
     respond_to do |format|
-      format.html # show.html.erb
-      format.txt # show.txt.erb
+      format.html { cache }
+      format.txt { cache }
     end
   end
 
@@ -57,7 +56,7 @@
   def destroy
     @paste = Paste.safe_find(params[:id])
     if @paste.safe_destroy(params[:paste][:key])
-      expire_page :controller => 'pastes', :action => 'show', :id => @paste.id
+      uncache
       redirect_to root_path, :notice => "Paste ##{params[:id]} deleted"
     else
       flash.now[:alert] = @paste.errors.full_messages.to_sentence
@@ -66,6 +65,37 @@
   end
 
   private
+
+  def lowercase_path
+    correct_path = request.fullpath.downcase
+    redirect_to correct_path, :status => :moved_permanently  unless
+      correct_path == request.fullpath
+  end
+
+  def cache_key(format = request.format)
+    ext = case format
+          when Mime::TXT
+            ".txt"
+          when Mime::HTML
+            ""
+          else
+            ".unknown"
+          end
+    "pastes:#{@paste.to_param}#{ext}"
+  end
+
+  def cache
+    Rails.cache.fetch cache_key, :raw => true do
+      render_to_string :show
+    end
+  end
+
+  def uncache
+    [Mime::TXT, Mime::HTML, "others"].each do |format|
+      Rails.cache.delete cache_key(format)
+    end
+  end
+
   def paste_params
     params.require(:paste).permit(:paste, :paste_gzip, :paste_gzip_base64, :is_private, :key)
   end