#90 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.
Resources
products_controller.rb
cache_sweeper :product_sweeper, :only => [:create, :update, :destroy]
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
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.action_controller.perform_caching = true
config/environment.rb
config.load_paths << "#{RAILS_ROOT}/app/sweepers"
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
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
rhtml
<% 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 %>
<% 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 %>

