gpt4 book ai didi

ruby-on-rails - 为什么需要在 Controller 中声明缓存清扫器?

转载 作者:数据小太阳 更新时间:2023-10-29 08:10:04 26 4
gpt4 key购买 nike

缓存清扫器是一个观察者,在它观察的模型上有一些钩子(Hook):

class MySweeper < ActionController::Caching::Sweeper
observe MyModel

def after_update(my_model)
expire_page(...)
end
end

但是文档和指南也说要在 Controller 中声明清扫器:

class ApplicationController < ActionController::Base
cache_sweeper :my_sweeper
end

这是为什么?观察者的目的不是观察模型并采取行动吗? Controller 难道不需要知道缓存何时过期或导致过期的原因吗?

澄清

我对将清扫器设置为观察者的理解是,这意味着“在所有情况下,当更新 MyModel 时,运行此清理代码”

  1. 准确吗?
  2. 如果是这样,那么为什么 cache_sweeper :my_sweeper 也需要在 Controller 中声明?那有什么作用?

最佳答案

来自缓存清扫器文档:

Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change.

They do this by being half-observers, half-filters and implementing callbacks for both roles.

Sweeper 使用 Controller 使缓存过期、获取缓存设置等。看看 source code .因此,缓存清扫器允许我们从 Controller 端控制缓存。我认为这很好,因为我们可以在发生任何事件时使缓存过期 - 数据库更改或用户登录或其他任何事件。

我认为,如果你不想在 Controller 中调用cache_sweeper 方法,你可以在你的清扫器中定义controller 方法。我没有测试以下代码,但它应该可以工作,因为我在扫地机规范中做了同样的事情。

class MySweeper < ActionController::Caching::Sweeper
observe MyModel

def after_update(my_model)
expire_page(...)
end

def controller
@controller ||= ActionController::Base.new
end
end

关于ruby-on-rails - 为什么需要在 Controller 中声明缓存清扫器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10521647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com