如何判断缓存是否正常工作.Rails 4

7 ruby caching ruby-on-rails ruby-on-rails-4

我正在关注"使用Rails 4进行敏捷Web开发"指南并进入了一个关于缓存的部分.以下是要遵循的步骤:

  1. 在config/environments/development.rb中

    config.action_controller.perform_caching = true
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在app/models/product.rb中

    def self.latest
        Product.order(:updated_at).last
    end
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在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 %>
    
    Run Code Online (Sandbox Code Playgroud)

为了验证现金是否有效,该书说:"至于验证这是否有效,不幸的是没有太多可看的.如果你去那个页面,你应该看到没有任何变化,这实际上是重点!您可以做的最好是在缓存块内的任何位置更改模板,而不更新任何产品并验证您没有看到该更新,因为页面的缓存版本尚未更新".

但是,当我尝试在缓存块中的代码中添加"Hello"字符串时,它会出现在页面上.我已经完成了所有服务器重启,什么不是.

但是,当我在本地主机上重新加载页面时,我确实看到了这一行

    Cache digest for app/views/store/index.html.erb: 6c620ede1d4e824439a7b0e3b177620f
Run Code Online (Sandbox Code Playgroud)

当我有config.action_controller.perform_caching = false时,这不是他们的

链接到git hub repo:https://github.com/BrianLobdell/depot

谢谢你,Brian

Ste*_*fan 2

Rails 在更改文件时更新缓存,因此更容易操作缓存。

您可以使用 Rails 控制台中页面的缓存摘要来检索缓存片段(摘要可能已更改,请确保使用最新的!):

key = ['store', Product.latest, '6c620ede1d4e824439a7b0e3b177620f']
ActionController::Base.new.read_fragment(key)
Run Code Online (Sandbox Code Playgroud)

这应该返回缓存的片段。为了确保 Ruby 在提供页面时实际命中缓存,您可以用一些其他内容替换该片段:

ActionController::Base.new.write_fragment(key, 'it works!')
Run Code Online (Sandbox Code Playgroud)

重新加载页面,您应该看到“它有效!”