---
title: "Ruby on Rails实战之一：巧妙解决页面片段缓存陷阱"
author: "rubyrock"
date: "2009-05-24T00:39:01Z"
tags: []
slug: "ruby-on-rails"
draft: false
lastmod: "2009-06-05T14:16:20Z"
id: 394381
url: "https://rubyrock.iteye.com/blog/394381"
---

Rails的片段缓存fragment cache有一个很隐蔽的陷阱。在Rubyconf China 2009会上，牛人Robin Lu向大家详细讲解了这个陷阱（他演讲的ppt在[http://www.scribd.com/doc/15705678/Ruby-on-Rails-Pitfall?autodown=pdf](http://www.scribd.com/doc/15705678/Ruby-on-Rails-Pitfall?autodown=pdf) 可以看到），最后也提出了3种解决方案，不过我觉得这3种方案都不太令人满意，下面分享一下我的解决方案。

 

首先，有必要简单介绍一下Rails的这个片段缓存陷阱。大家先看一下代码：

 

```
#code in the controller

class BlogController < ApplicationController
   def list
       unless read_fragment("/blog/list/articles")
           @articles = Article.find(:all)
       end
   end 
end

#code in the view
<% cache("/blog/list/articles") do %>
  <ul>
  <% for article in @articles do %>
     <li> <p> <%=h(article.body)%> </p></li>
   <% end %>
  </ul>
<% end %>

```

这是很多人使用片段缓存的做法，大概是受了那本经典教程影响的缘故。在并发量不大的情况下，这段代码不会产生问题，但是在并发量一大很容易会crash，提示信息是@articles未赋值。其原因在于，在action中检查缓存和view中使用缓存中间存在时间间隔。设想一下:一个过程在action中found cache，于是未获取@articles，但是执行到view时，缓存被另外的进程清空了，这个时候使用@articles就会报异常。

 

Robin提到的三种方法是：

1.处理异常，提示用户刷新页面。这种方法对用户体验而言，不友好。

2.在view处理的地方获取@articles。这种方法让view中充斥代码，不优雅。

3.更新缓存内容而不是清空缓存。这种方法需要额外处理，不爽。

 

我的解决方法**其实非常简单** ，**改写cache方法和fragment\_exists?方法，在action中使用fragment\_exists?检查缓存，如果找到，就把读到的内容置到实例变量中，在view的cache方法中，使用该实例变量。** 多说无益，看一下代码

就明白了。

插件smart\_fragment\_cache 中的核心代码

```
module ActionController #:nodoc:
  module Caching
    module Fragments       
      #override fragment_exist?
      def fragment_exists?(name, options=nil)
        @internal_smart_caches ||= {}
        key = fragment_cache_key(name)
        @internal_smart_caches[key] = read_fragment(name, options)    
      end      
      
      #cache_miss?
      def fragment_miss?(name, options=nil)
         !fragment_exists?(name,options)       
      end
      
      #override fragment_for
      def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc:
        if perform_caching
          if cache = smart_read_fragment(name, options)
            buffer.concat(cache)
          else
            pos = buffer.length
            block.call
            write_fragment(name, buffer[pos..-1], options)
          end
        else
          block.call
        end
      end      
      
      #smart_read_fragment
      def smart_read_fragment(name, options=nil)
          key = fragment_cache_key(name)
          (@internal_smart_caches and @internal_smart_caches[key]
) or read_fragment(name, options)     
      end
    end
  end
end
```

 

使用插件后，刚才的代码改写成

```
#code in the controller

class BlogController < ApplicationController
   def list
       unless fragment_exists?("/blog/list/articles")
           @articles = Article.find(:all)
       end
   end 
end

#code in the view
<% cache("/blog/list/articles") do %>
  <ul>
  <% for article in @articles do %>
     <li> <p> <%=h(article.body)%> </p></li>
   <% end %>
  </ul>
<% end %>
```

 

代码只有一处细小变化，action中 read\_fragment 变为 fragment\_exists?。使用这个方案，有三个好处：

**1.检查和使用缓存数据只发生一次，高并发下不会触发异常，更安全;**

**2.只执行一次获取缓存动作，更高效;**

**3.不需要额外处理，同时保持了view中代码清洁，更优雅。**

 

插件 smart\_fragment\_cache刚刚写成，目前只针对 Rails 2.3.2版本，先提供附件下载吧，等我弄好后再正式发布出来，希望对大家有帮助。