fragment caching เป็น post ต่อจาก page caching กับ action caching
ชื่อมันก็บอกอยู่แล้วว่าทำ cache แบบเป็นชิ้นๆ สิ่งที่นิยมทำ cache แบบนี้คือการ render เป็นส่วนๆ ในฝั่งของ html template ตัวอย่าง
1 2 3 4 5 | <b><%= @title %></b> <% cache do %> a lot of text or ruby expression hear and it is <%= render :partial => "topic", :locals => {:time => Time.now } %> <% end %> |
ในที่นี้ มันจะ cache ใน block ที่กำหนดไว้ โดยค่า default ในการอ้างถึงจะเป็นชื่อ action และ controller เช่น ถ้าจะ clear cache ก้อนนี้ จะเรียกใช้
expire_fragment(:controller => "topics", :action => "list")
ในความเป็นจริงแล้ว เราอาจจะมี cache หลายที่ในหนึ่งหน้า เลยมี options เพิ่มมา สำหรับกำหนดชื่อให้มันอีก
1
| cache(:action => "list", :action_suffix => "time") |
ตัว action_suffix จะเป็นสิ่งที่ทำให้เราสามารถเข้าถึง cache ก้อนนี้ได้ เช่น
expire_fragment(:controller => "topics", :action => "list", :action_suffix => "time")
แล้วมันเอาไปเก็บไว้ที่ไหน??
จริงๆ ผมเขียนไปในตอนที่แล้วแล้ว ว่ามันเก็บไว้เป็น hash โดยใช้ ActiveSupport::Cache::MemoryStore เป็นตัวบันทึก
รายละเอียดเพิ่มเติมดูได้ใน API ได้เลย