#90
Jan 27, 2008

Fragment Caching

Sometimes you only want to cache a section of a page instead of the entire page. Fragment caching is the answer as shown in this episode.
Download (20.5 MB, 6:54)
alternative download for iPod & Apple TV (11.4 MB, 6:54)

Resources

# products_controller.rb
cache_sweeper :product_sweeper, :only => [:create, :update, :destroy]

# models/product.rb
class Product < ActiveRecord::Base
  def self.find_recent
    find(:all, :order => 'released_at desc', :limit => 10)
  end
end

# config/environments/development.rb
config.action_controller.perform_caching = true

# config/environment.rb
config.load_paths << "#{RAILS_ROOT}/app/sweepers"

# sweepers/product_sweeper.rb
class ProductSweeper < ActionController::Caching::Sweeper
  observe Product
  
  def after_save(product)
    expire_cache(product)
  end
  
  def after_destroy(product)
    expire_cache(product)
  end
  
  def expire_cache(product)
    expire_fragment 'recent_products'
  end
end
<% cache 'recent_products' do %>
<div id="recent_products">
  <h2>Recent Products</h2>
  <ul>
  <% for product in Product.find_recent %>
    <li><%= link_to h(product.name), product %></li>
  <% end %>
  </ul>
</div>
<% end %>

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source