File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -99,18 +99,52 @@ 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 = Rails.cache.read_multi(*cache_keys)
114+
103115 items.each_with_index do |item, index|
104116 options = options.merge("#{ name } " => item, "#{ counter } " => index + 1)
105117 presenter = ::#{ item_presenter_class } .new(self, options)
118+
119+ if cached_fragments.key?(presenter.cache_key)
120+ buffers.last << cached_fragments[presenter.cache_key]
121+ next
122+ end
123+
124+ render_with_caching = proc do |&block|
125+ value = block.call
126+
127+ if presenter.cache_key
128+ Rails.cache.write(presenter.cache_key, value)
129+ end
130+
131+ value
132+ end
133+
134+ buffers.last << render_with_caching.call do
135+ buffer = ActiveSupport::SafeBuffer.new
106136 RUBY
107137
108138 @presenter_classes . push ( item_presenter_class )
109139 compile ( block . nodes )
110140 @presenter_classes . pop
111141
112142 output <<-RUBY
143+ buffer
144+ end
113145 end
146+
147+ buffer = buffers.pop
114148 options = options_stack.pop
115149 presenter = presenters.pop
116150 RUBY
Original file line number Diff line number Diff line change 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
7893end
You can’t perform that action at this time.
0 commit comments