From ca9622cca30c1112dd4408fcb2e658849abe1dd5 Mon Sep 17 00:00:00 2001 From: Kai Chen Date: Fri, 6 Jun 2014 09:41:35 +0800 Subject: [PATCH] fix cache key generation for complex object In Rails > 4, cache key would be expand fragment name with digest. https://github.com/rails/rails/blob/4-0-stable/actionpack/lib/action_view/helpers/cache_helper.rb#L115 https://github.com/rails/rails/blob/4-0-stable/actionpack/lib/action_controller/caching/fragments.rb#L21-23 --- lib/jbuilder/jbuilder_template.rb | 11 ++++++++--- test/jbuilder_template_test.rb | 14 ++------------ 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/lib/jbuilder/jbuilder_template.rb b/lib/jbuilder/jbuilder_template.rb index 2f1027c..472bc12 100644 --- a/lib/jbuilder/jbuilder_template.rb +++ b/lib/jbuilder/jbuilder_template.rb @@ -98,6 +98,13 @@ def _render_partial(options) end def _cache_key(key, options) + key = fragment_name_with_digest(key, options) + ::ActiveSupport::Cache.expand_cache_key(key.is_a?(::Hash) ? url_for(key).split('://').last : key, :jbuilder) + end + + private + + def fragment_name_with_digest(key, options) if @context.respond_to?(:cache_fragment_name) # Current compatibility, fragment_name_with_digest is private again and cache_fragment_name # should be used instead. @@ -106,12 +113,10 @@ def _cache_key(key, options) # Backwards compatibility for period of time when fragment_name_with_digest was made public. @context.fragment_name_with_digest(key) else - ::ActiveSupport::Cache.expand_cache_key(key.is_a?(::Hash) ? url_for(key).split('://').last : key, :jbuilder) + key end end - private - def _mapable_arguments?(value, *args) return true if super options = args.last diff --git a/test/jbuilder_template_test.rb b/test/jbuilder_template_test.rb index 118d67a..c7d6efa 100644 --- a/test/jbuilder_template_test.rb +++ b/test/jbuilder_template_test.rb @@ -246,6 +246,7 @@ def assert_collection_rendered(json, context = nil) undef_context_methods :fragment_name_with_digest @context.expects :cache_fragment_name + ActiveSupport::Cache.expects :expand_cache_key render_jbuilder <<-JBUILDER json.cache! 'cachekey' do @@ -258,6 +259,7 @@ def assert_collection_rendered(json, context = nil) undef_context_methods :fragment_name_with_digest @context.expects(:cache_fragment_name).with('cachekey', skip_digest: true) + ActiveSupport::Cache.expects :expand_cache_key render_jbuilder <<-JBUILDER json.cache! 'cachekey', skip_digest: true do @@ -277,16 +279,4 @@ def assert_collection_rendered(json, context = nil) assert_equal Rails.cache.inspect[/entries=(\d+)/, 1], '0' end - test 'fragment caching falls back on ActiveSupport::Cache.expand_cache_key' do - undef_context_methods :fragment_name_with_digest, :cache_fragment_name - - ActiveSupport::Cache.expects :expand_cache_key - - render_jbuilder <<-JBUILDER - json.cache! 'cachekey' do - json.name 'Cache' - end - JBUILDER - end - end