[Rails 常用插件简介]Sweeper Generator

cache是系统中必不可少的东西,那么cache的有效期,何时清除过时的cache就显得更加有意思的一个话题。Sweeper Generator 顾名思义是一个Generator,清除过时的cache

0:) cache
Rails中目前有三种cache
caches_pages
caches_action
caches_fragment

cache还不懂?那就先收藏着吧,等下次有时间开个专题讨论一下cache,这里就不废话了。

1:) 安装
[code]ruby script/plugin install http://topfunky.net/svn/plugins/sweeper[/code]

2:) 使用
运行
[code]
ruby script\generate
[/code]
可以看到sweeper
[code]Installed Generators
Plugins: sweeper
[/code]

我们使用cache Fragment在页面上缓存论坛分类
[code]<% cache(cache_key('categories')) do -%>
....
<%end%>[/code]

启动server,浏览页面,第一次运行会看到
[code]
Cached fragment: localhost:3000/cache/categories (0.00000)
[/code]
同时在cache目录下找到 categories .cache文件,打开浏览,你会看到正式你浏览页面的html文件

刷新页面,再次浏览,会看到
[code]
Fragment read: localhost:3000/cache/categories (0.00000)
[/code]

执行查询分类的sql已经不在运行了,仅仅是读取cache的文件而已。

ok,转到后台,新增分类,再转前台,刷新
[code]
Fragment read: localhost:3000/cache/categories (0.00000)
[/code]

刚才添加的新分类怎么没了??

是缓存的原因,当前的页面片段存在缓存,而我们刚才新增加的分类后,并没有删除过时的cache,手工删除categories.cache,再删除
[code]
Cached fragment: localhost:3000/cache/categories (0.00000)
[/code]
OK,成功了。

可是这样繁琐了点:(

不怕:) rails自有利器,该Observer发挥作用了 (Observer是什么?OH, NO,这个,建议你没事看看设计模式,简单点说就是一个观察着模式),而Sweeper用的也是这个

先来看一下Sweeper Generator的usage
[code]
./script/generate sweeper SweeperName callback1 callback2
[/code]

OK,我们来生成我们想要的东西
[code]
ruby script/generate sweeper Record after_save after_update after_destroy
[/code]

生成
[code]
class RecordSweeper < ActionController::Caching::Sweeper
def after_save(record)
end

def after_update(record)
end

def after_destroy(record)
end
end
[/code]

添加我们观察的对象
[code]
observe Forum
[/code]

当新建forum时候,我们删除掉过时的cache
[code]
def after_save(record)
expire_fragment(cache_key('categories'))
end
[/code]

在你的environment中添加
config.active_record.observers = :record_sweeper

现在转到后台,新增分类测试下。当提交时,会发现console多了几条信息

[code]
Expired fragment: localhost:3000/cache/categories (0.00000)
[/code]
cache已经清楚了

再次浏览index会发现重新生成了cache
[code]
Cached fragment: localhost:3000/cache/categories (0.00000)
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值