[Feature Request] Error if `content_for` called from within fragment cache

47 views
Skip to first unread message

Michael Pearson

unread,
Feb 24, 2017, 12:06:36 PM2/24/17
to Ruby on Rails: Core
Hi all,

This was originally incorrectly posted at https://github.com/rails/rails/issues/28072 - as advised, I'm now posting it here instead.

It is very easy to accidentally call content_for from within a block that will be fragment cached, especially if the cached fragment calls out to a partial. eg:

<!-- index.html.erb -->
<%= cache "fragment" do %>
  <!-- ... -->
  <%= render "javascript_widget" %>
<% end %>
<!-- load javascript files last -->
<%= content_for :javascript_includes %>

<!--- _javascript_widget.html.erb -->
<div class="jsPlaceholder />
<% content_for :javascript_includes do %>
  <%= javascript_include_tag ... %>
  <script>doTheThing('.jsPlaceholder')</script>
<% end %>

Steps to reproduce
Call content_for from within code that will end up in a fragment cache

Expected behavior
An error should be raised letting the developer know that the content_for would not occur.

Actual behavior
The contents of the content_for are silently discarded.

Matthew Draper

unread,
Feb 24, 2017, 12:24:14 PM2/24/17
to rubyonra...@googlegroups.com

> Call content_for from within code that will end up in a fragment cache
>
> An error should be raised letting the developer know that the content_for would not occur.


Sounds sensible to me.


The only danger that comes to mind is if someone is using content_for to pass information around between two chunks within a cached fragment — that would currently be working fine, and the error would break it.

Maybe we can raise specifically if you try to fetch content across a cache boundary. Or maybe we don’t need to care about that.


If someone would like to work up a PR to do one or both of the above, please do go ahead 👍🏻


Matthew


--
mat...@trebex.net
Reply all
Reply to author
Forward
0 new messages