Skip to content

Commit 9b209e8

Browse files
committed
read_ and write_fragment cache preserve html safety yet cache strings only
1 parent 056f957 commit 9b209e8

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

actionpack/lib/action_controller/caching/fragments.rb

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,7 @@ def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc:
4141
else
4242
pos = buffer.length
4343
block.call
44-
content = buffer[pos..-1]
45-
content = content.as_str if content.respond_to?(:as_str)
46-
write_fragment(name, content, options)
44+
write_fragment(name, buffer[pos..-1], options)
4745
end
4846
else
4947
block.call
@@ -54,9 +52,9 @@ def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc:
5452
def write_fragment(key, content, options = nil)
5553
return content unless cache_configured?
5654

57-
key = fragment_cache_key(key)
58-
5955
self.class.benchmark "Cached fragment miss: #{key}" do
56+
key = fragment_cache_key(key)
57+
content = content.html_safe.as_str if content.respond_to?(:html_safe)
6058
cache_store.write(key, content, options)
6159
end
6260

@@ -67,10 +65,10 @@ def write_fragment(key, content, options = nil)
6765
def read_fragment(key, options = nil)
6866
return unless cache_configured?
6967

70-
key = fragment_cache_key(key)
71-
7268
self.class.benchmark "Cached fragment hit: #{key}" do
73-
cache_store.read(key, options)
69+
key = fragment_cache_key(key)
70+
result = cache_store.read(key, options)
71+
result.respond_to?(:html_safe) ? result.html_safe : result
7472
end
7573
end
7674

actionpack/test/controller/caching_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,20 @@ def test_fragment_for
621621
assert !fragment_computed
622622
assert_equal 'generated till now -> fragment content', buffer
623623
end
624+
625+
def test_html_safety
626+
assert_nil @store.read('views/name')
627+
content = 'value'.html_safe
628+
assert_equal content, @controller.write_fragment('name', content)
629+
630+
cached = @store.read('views/name')
631+
assert_equal content, cached
632+
assert_equal String, cached.class
633+
634+
html_safe = @controller.read_fragment('name')
635+
assert_equal content, html_safe
636+
assert html_safe.html_safe?
637+
end
624638
end
625639

626640
class FunctionalCachingController < ActionController::Base

0 commit comments

Comments
 (0)