user3133810
user3133810

Reputation:

How to tell if Caching is working. Rails 4

I am following along with the 'Agile Web Development with Rails 4' guide and have come to a section on caching. Here are the steps to follow:

  1. in config/environments/development.rb

    config.action_controller.perform_caching = true
    
  2. In app/models/product.rb

    def self.latest
        Product.order(:updated_at).last
    end
    
  3. in views/store/index.html.erb

    <% 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 %>
    

To verify the cash is working, the book says: "As far as verifying that this works, unfortunately there isn't much to see. If you go to that page, you should see nothing change, which in fact is the point! The best you can do is to make a change to the template anywhere inside the cache block without updating any product and verifying that you do not see that update because the cached version of the page has not been updated".

However, when I try and add a "Hello" string in the code within the cache blocks, it appears on the page. I've done all the server restarting and what not.

But, when I reload the page on my local host I do see this line

    Cache digest for app/views/store/index.html.erb: 6c620ede1d4e824439a7b0e3b177620f

which is not their when I have config.action_controller.perform_caching = false

Link to git hub repo: https://github.com/BrianLobdell/depot

Thank you, Brian

Upvotes: 7

Views: 3675

Answers (1)

Stefan
Stefan

Reputation: 114208

Rails updates the cache when changing the file, so it's easier to manipulate the cache instead.

You can retrieve the cache fragment using the cache digest for the page in your Rails console (the digest might have changed, make sure to use the recent one!):

key = ['store', Product.latest, '6c620ede1d4e824439a7b0e3b177620f']
ActionController::Base.new.read_fragment(key)

This should return the cached fragment. To ensure that Ruby actually hits the cache when serving the page, you could replace the fragment with some other content:

ActionController::Base.new.write_fragment(key, 'it works!')

Reload the page, you should see "it works!".

Upvotes: 2

Related Questions