Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: what does cache['store', Product.latest] function do in fragment cache?

I'm following a book called Agile Web Development With Rails 4 and I'm having problem while understanding what does cache ['store', Product.latest] do in the view file.

#static function latest is defined in the model
def self.latest
  Product.order(:updated_at).last
end

#here is my view file

<% cache['store',Product.latest] do %>
 <% @products.each do|product| %>
  <% cache['entry',product] do %>
     <div class="entry">
      <%= image_tag(product.image_url) %>
      <h3><%= product.title %></h3>
      <%= sanitize(product.description) %>
      <div class="price_line">
       <span class="price"><%= number_to_currency(product.price) %></span>
      </div>
    </div>
  <% end %>
 <% end %>
<% end %>
like image 685
Ejaz Karim Avatar asked Nov 09 '22 20:11

Ejaz Karim


1 Answers

The cache(key) { ... } helper performs the content of the block, and cached the result with the given key for a certain amount of time.

The documentation explain in details all the various options and features.

In your case, ['store',Product.latest] are the parameters that build the cache key name. The items in the array are joined to produce a String similar to store/products/100-20140101-163830 that is then used as the cache key to store the result of the block.

The reason why Product.latest is passed as argument of the cache key, is a trick to make sure the fragment is expired as soon as a new product is added to the database. This approach is often referred as key-based expiration model.

like image 158
Simone Carletti Avatar answered Nov 15 '22 04:11

Simone Carletti