From 729ed78236765ef88fb03c839fc1088b9c1cfad5 Mon Sep 17 00:00:00 2001 From: Jacob Evan Shreve Date: Fri, 4 Nov 2016 19:27:40 -0400 Subject: [PATCH] Fix custom cache key mechanism According to the docs, multi_fetch_fragments supports the shorthand syntax, `render @items, cache: true`. This is true for boolean values, but does not support custom cache keys via proc or lambda values. This is because the shorthand passes cache to @locals rather than @options, and the search for the callable object is limited to @options. This commit adds @locals to that search. --- lib/multi_fetch_fragments.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/multi_fetch_fragments.rb b/lib/multi_fetch_fragments.rb index db36d04..0d27365 100644 --- a/lib/multi_fetch_fragments.rb +++ b/lib/multi_fetch_fragments.rb @@ -6,6 +6,7 @@ module MultiFetchFragments end private + def render_collection_with_multi_fetch_cache return nil if @collection.blank? @@ -22,7 +23,7 @@ def render_collection_with_multi_fetch_cache keys_to_collection_map = {} @collection.each do |item| - key = @options[:cache].respond_to?(:call) ? @options[:cache].call(item) : item + key = cache_option.respond_to?(:call) ? cache_option.call(item) : item key_with_optional_digest = nil if defined?(@view.fragment_name_with_digest) @@ -33,7 +34,6 @@ def render_collection_with_multi_fetch_cache key_with_optional_digest = key end - expanded_key = fragment_cache_key(key_with_optional_digest) keys_to_collection_map[expanded_key] = item @@ -78,12 +78,15 @@ def render_collection_with_multi_fetch_cache results.join(spacer).html_safe end + def cache_option + @options[:cache] || @locals[:cache] + end + def cache_collection? - cache_option = @options[:cache].presence || @locals[:cache].presence ActionController::Base.perform_caching && cache_option end - # from Rails fragment_cache_key in ActionController::Caching::Fragments. Adding it here since it's tucked inside an instance method on the controller, and + # from Rails fragment_cache_key in ActionController::Caching::Fragments. Adding it here since it's tucked inside an instance method on the controller, and # it's utility could be used in a view without a controller def fragment_cache_key(key) ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)