Module: ActionView::Helpers::CacheHelper
- Defined in:
- lib/interlock/action_view.rb
Instance Method Summary collapse
-
#view_cache(*args, &block) ⇒ Object
(also: #caching)
view_cachemarks a corresponding view block for caching.
Instance Method Details
#view_cache(*args, &block) ⇒ Object Also known as: caching
view_cache marks a corresponding view block for caching. It accepts :tag and :ignore keys for explicit scoping, as well as a :ttl key and a :perform key.
You can specify dependencies in view_cache if you really want to. Note that unlike behavior_cache, view_cache doesn’t set up any default dependencies.
Nested view_cache blocks work fine. You would only need to nest if you had a slowly invalidating block contained in a more quickly invalidating block; otherwise there’s no benefit.
Finally, caching content_for within a view_cache works, unlike regular Rails. It even works in nested caches.
Setting a TTL
Use the :ttl key to specify a maximum time-to-live, in seconds:
<% view_cache :ttl => 5.minutes do %>
<% end %>
Note that the cached item is not guaranteed to live this long. An invalidation rule could trigger first, or memcached could eject the item early due to the LRU.
View caching without action caching
It’s fine to use a view_cache block without a behavior_cache block. For example, to mimic regular fragment cache behavior, but take advantage of memcached’s :ttl support, call:
<% view_cache :ignore => :all, :tag => 'sidebar', :ttl => 5.minutes do %>
<% end %>
Dependencies, scoping, and other options
See ActionController::Base for explanations of the rest of the options. The view_cache and behavior_cache APIs are identical except for setting the :ttl, which can only be done in the view, and the default dependency, which is only set by behavior_cache.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/interlock/action_view.rb', line 41 def view_cache(*args, &block) # conventional_class = begin; controller.controller_name.classify.constantize; rescue NameError; end , dependencies = Interlock.(args, nil) key = controller.caching_key(.value_for_indifferent_key(:ignore), .value_for_indifferent_key(:tag)) if [:perform] == false || Interlock.config[:disabled] # Interlock.say key, "is not cached" block.call else Interlock.register_dependencies(dependencies, key) # Interlock.say key, "is rendering" @cached_content_for, previous_cached_content_for = {}, @cached_content_for cache key, :ttl => (.value_for_indifferent_key(:ttl) or Interlock.config[:ttl]), &block # This is tricky. If we were already caching content_fors in a parent block, we need to # append the content_fors set in the inner block to those already set in the outer block. if previous_cached_content_for @cached_content_for.each do |key, value| previous_cached_content_for[key] = "#{previous_cached_content_for[key]}#{value}" end end # Restore the cache state @cached_content_for = previous_cached_content_for end end |