Added support for conditional fragment caching using :if and :unless options. #5396

Closed
wants to merge 6 commits into
from
View
6 actionpack/lib/action_view/helpers/cache_helper.rb
@@ -104,7 +104,7 @@ module CacheHelper
#
# Now all you'll have to do is change that timestamp when the helper method changes.
def cache(name = {}, options = nil, &block)
- if controller.perform_caching
+ if controller.perform_caching && options_pass_conditions?(options)
safe_concat(fragment_for(fragment_name_with_digest(name), options, &block))
else
yield
@@ -142,6 +142,10 @@ def fragment_for(name = {}, options = nil, &block) #:nodoc:
controller.write_fragment(name, fragment, options)
end
end
+
+ def options_pass_conditions?(options) #:nodoc:
+ !(options && (!options.fetch(:if, true) || options.fetch(:unless, false)))
+ end
end
end
end
View
14 actionpack/test/controller/caching_test.rb
@@ -146,6 +146,20 @@ def test_html_safety
assert_equal content, html_safe
assert html_safe.html_safe?
end
+
+ def test_conditional_fragment_caching
+ @controller.write_fragment('name', 'fragment content')
+ if_fragment_computed = false
+ unless_fragment_computed = false
+
+ view_context = @controller.view_context
+
+ view_context.send(:cache, 'name', { if: false }) { if_fragment_computed = true }
+ view_context.send(:cache, 'name', { unless: true }) { unless_fragment_computed = true }
+
+ assert if_fragment_computed
+ assert unless_fragment_computed
+ end
end
class FunctionalCachingController < CachingController