Allow collection cache invalidation on new collection entries

I faced recently an issue in our app, regarding collection caching. I wrongly assumed that collections were invalidated when new entries were added to the collection. I am using the really helpful iterators variables available locally in the template to show information, on a carousel for instance:

# app/views/pictures/_picture.html.erb 
<% index = picture_iteration.index %>
<% size = picture_iteration.size %>

<li class="carousel-slide"> 
  <img src="..." /> 
  <span class="legend"><%= picture.name %> (<%= index + 1 %>/<%= size %>)</span>
</li> 

For performance, I am caching the collection

# app/views/pictures/index.html.erb 
<%= render partial: "public/venues/picture", collection: @venue.pictures, cached: true %>

If new pictures are added or, some are evicted from the cache, iterators become incoherent. Indeed, only non-cached entry will be taken into account in the size and index variables, and old entries will have wrong size values saved in the cached template .

I am proposing the following change available in this PR, allowing one to invalidate the collection cache when a new entry is added to the collection; when the invalidate_cache_on_new_entry option is specified on the collection render call.

This is my first PR and feature proposal on Rails, let me know if you need more information / I can improve the problem statement.

Cheers, Vincent