Ruby on Rails :: Action Caching
Posted by PunNeng, Sun Oct 26 21:09:00 UTC 2008
ต่อจากคราวที่แล้ว
ใน API ของ rails เอง เขียนอธิบายไว้ว่า มันไม่ได้ต่างอะไรกับ page caching มาก แต่ผมว่ามันค่อนข้างต่างเลยแหละ ถ้าจะพิจารณาการบันทึกข้อความสำหรับ cache
เรื่อง configuration ก็เหมือนกับ page caching ครับ จะข้ามไป
แล้ว Action Caching ใช้ตอนไหน ??
ก็ใช้ตอนที่เราต้องใช้ filter เช่น before_filter หรือ after_filter
ตัวอย่างที่เขาใช้อธิบายใน API คือ เรือ่ง authentication ใน code หน้าตาจะประมาณนี้
1 2 3 4 5 | class ListsController < ApplicationController before_filter :authenticate, :except => :public caches_page :public caches_action :index, :show, :feed end |
จากตัวอย่างข้างบน จะมีการ authentication ที่ action index, show และ feed
ถ้าหากไม่ใช้ caches_action แต่ไปใช้ caches_page แทน มันจะเขียน file.html แล้วมันจะไม่วิ่งเข้า before_filter :authetication
ทางแก้ก็คือ ใช้ caches_action แทน
โดยการเก็บ cache มันจะไปใช้ความสามารถของ Fragment Cache แทน สำหรับ Fragment Cache ไว้ตอนหน้าครับ ซึ่งมันจะเก็บ cache ไว้ที่ Hash ไว้ใน ActiveSupport::Cache::MemoryStore ครับ ถ้าเรา restart server มันก็จะหายไป ไม่ได้เก็บถาวรเหมือน Page Caching
ในการ clear action caching ก็ไม่ได้ซับซ้อนอะไร เพียงแค่
1
| expire_action :controller =>"lists", :action => "index" |
นอกจากนี้ยังใส่เงื่อนไขได้ด้วย เช่น
1 2 3 4 5 6 7 8 9 10 | class ListsController < ApplicationController before_filter :authenticate, :except => :public caches_page :public caches_action :index, :if => Proc.new { |c| !c.request.format.json? } # cache if is not a JSON request caches_action :show, :cache_path => { :project => 1 } caches_action :feed, :cache_path => Proc.new { |controller| controller.params[:user_id] ? controller.send(:user_list_url, c.params[:user_id], c.params[:id]) : controller.send(:list_url, c.params[:id]) } end |
ข้อมูลเพิ่มเติมดูได้ที่ API เลยครับ