Skip to content

Commit ba4f671

Browse files
committed
wip
1 parent 30f22a7 commit ba4f671

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

lib/curly/compiler.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,18 +99,56 @@ def compile_collection(block)
9999
output <<-RUBY
100100
presenters << presenter
101101
options_stack << options
102+
buffers << buffer
103+
102104
items = Array(#{method_call})
105+
106+
cache_keys = items.each_with_index.map {|item, index|
107+
options = options.merge("#{name}" => item, "#{counter}" => index + 1)
108+
item_presenter_key = ::#{item_presenter_class}.new(self, options).cache_key
109+
110+
ActiveSupport::Cache::expand_cache_key(item_presenter_key) if item_presenter_key.present?
111+
}.compact
112+
113+
cached_fragments = unless cache_keys.empty?
114+
Rails.cache.read_multi(*cache_keys)
115+
else
116+
{}
117+
end
118+
103119
items.each_with_index do |item, index|
104120
options = options.merge("#{name}" => item, "#{counter}" => index + 1)
105121
presenter = ::#{item_presenter_class}.new(self, options)
122+
123+
if cached_fragments.key?(presenter.cache_key)
124+
buffers.last << cached_fragments[presenter.cache_key]
125+
next
126+
end
127+
128+
render_with_caching = proc do |&block|
129+
value = block.call
130+
131+
if presenter.cache_key
132+
Rails.cache.write(presenter.cache_key, value)
133+
end
134+
135+
value
136+
end
137+
138+
buffers.last << render_with_caching.call do
139+
buffer = ActiveSupport::SafeBuffer.new
106140
RUBY
107141

108142
@presenter_classes.push(item_presenter_class)
109143
compile(block.nodes)
110144
@presenter_classes.pop
111145

112146
output <<-RUBY
147+
buffer
148+
end
113149
end
150+
151+
buffer = buffers.pop
114152
options = options_stack.pop
115153
presenter = presenters.pop
116154
RUBY

spec/collection_blocks_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
def name
99
@item
1010
end
11+
12+
def cache_key
13+
@item
14+
end
1115
end
1216
end
1317

@@ -75,4 +79,15 @@ def number
7579

7680
render("{{*items}}<{{*parts}}[{{number}}]{{/parts}}>{{/items}}").should == "<[1][2]><[3][4]>"
7781
end
82+
83+
example "cached rendering" do
84+
define_presenter do
85+
def items
86+
["one", "two", "three"]
87+
end
88+
end
89+
90+
render("{{*items}}<{{name}}>{{/items}}").should == "<one><two><three>"
91+
render("{{*items}}<{{name}}>{{/items}}").should == "<one><two><three>"
92+
end
7893
end

0 commit comments

Comments
 (0)