2005-01-08 18:32:11 -05:00
|
|
|
module ActionView
|
2010-06-16 14:17:49 -04:00
|
|
|
# = Action View Cache Helper
|
2005-01-08 18:32:11 -05:00
|
|
|
module Helpers
|
|
|
|
module CacheHelper
|
2010-12-23 07:43:36 -05:00
|
|
|
# This helper exposes a method for caching fragments of a view
|
2011-05-10 18:36:00 -04:00
|
|
|
# rather than an entire action or page. This technique is useful
|
2010-12-23 07:43:36 -05:00
|
|
|
# caching pieces like menus, lists of newstopics, static HTML
|
|
|
|
# fragments, and so on. This method takes a block that contains
|
|
|
|
# the content you wish to cache.
|
2010-06-16 14:17:49 -04:00
|
|
|
#
|
2010-12-23 07:36:53 -05:00
|
|
|
# See ActionController::Caching::Fragments for usage instructions.
|
2007-06-23 13:49:18 -04:00
|
|
|
#
|
|
|
|
# ==== Examples
|
2010-12-23 07:36:53 -05:00
|
|
|
# If you want to cache a navigation menu, you can do following:
|
2007-06-23 13:49:18 -04:00
|
|
|
#
|
|
|
|
# <% cache do %>
|
|
|
|
# <%= render :partial => "menu" %>
|
|
|
|
# <% end %>
|
|
|
|
#
|
2010-12-23 07:36:53 -05:00
|
|
|
# You can also cache static content:
|
2007-06-23 13:49:18 -04:00
|
|
|
#
|
|
|
|
# <% cache do %>
|
|
|
|
# <p>Hello users! Welcome to our website!</p>
|
|
|
|
# <% end %>
|
|
|
|
#
|
2010-12-23 07:36:53 -05:00
|
|
|
# Static content with embedded ruby content can be cached as
|
|
|
|
# well:
|
2007-06-23 13:49:18 -04:00
|
|
|
#
|
|
|
|
# <% cache do %>
|
|
|
|
# Topics:
|
|
|
|
# <%= render :partial => "topics", :collection => @topic_list %>
|
|
|
|
# <i>Topics listed alphabetically</i>
|
|
|
|
# <% end %>
|
2008-01-03 16:05:12 -05:00
|
|
|
def cache(name = {}, options = nil, &block)
|
2010-06-07 20:54:53 -04:00
|
|
|
if controller.perform_caching
|
|
|
|
safe_concat(fragment_for(name, options, &block))
|
|
|
|
else
|
|
|
|
yield
|
|
|
|
end
|
|
|
|
|
2010-03-16 14:43:04 -04:00
|
|
|
nil
|
2005-01-08 18:32:11 -05:00
|
|
|
end
|
2010-03-18 18:52:43 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
# TODO: Create an object that has caching read/write on it
|
|
|
|
def fragment_for(name = {}, options = nil, &block) #:nodoc:
|
2010-09-16 12:44:18 -04:00
|
|
|
if fragment = controller.read_fragment(name, options)
|
|
|
|
fragment
|
2010-03-18 18:52:43 -04:00
|
|
|
else
|
2010-06-07 20:54:53 -04:00
|
|
|
# VIEW TODO: Make #capture usable outside of ERB
|
|
|
|
# This dance is needed because Builder can't use capture
|
|
|
|
pos = output_buffer.length
|
|
|
|
yield
|
2011-06-20 13:47:22 -04:00
|
|
|
output_safe = output_buffer.html_safe?
|
2011-06-20 12:32:47 -04:00
|
|
|
fragment = output_buffer.slice!(pos..-1)
|
2011-06-20 13:47:22 -04:00
|
|
|
if output_safe
|
2011-07-23 16:50:34 -04:00
|
|
|
self.output_buffer = output_buffer.class.new(output_buffer)
|
2011-06-08 01:07:39 -04:00
|
|
|
end
|
2010-06-07 20:54:53 -04:00
|
|
|
controller.write_fragment(name, fragment, options)
|
2010-03-18 18:52:43 -04:00
|
|
|
end
|
|
|
|
end
|
2005-01-08 18:32:11 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|