在Rails中,放置Sweeper
类的特定目录位置是否有约定?
更新:由于观察者被放置在app/models
中,我认为Sweeper也是一样的,只要名称始终以"sweeper"结尾。
在Rails中,放置Sweeper
类的特定目录位置是否有约定?
更新:由于观察者被放置在app/models
中,我认为Sweeper也是一样的,只要名称始终以"sweeper"结尾。
我喜欢将它们放在app/sweepers目录中。
我还将Presenters
放在app/presenters目录中...而将Observers
放在app/observers目录中。
app/models
目录中。缓存清除是一种机制,它允许您在代码中避免大量的 expire_{page,action,fragment} 调用。它通过将过期缓存内容所需的所有工作移动到 na ActionController::Caching::Sweeper 类中来实现这一点。此类是一个观察者,通过回调查找对象的更改,并在发生更改时在 around 或 after 过滤器中使与该对象相关联的缓存失效。
继续使用我们的 Product 控制器示例,我们可以像这样使用清除器进行重写:
class StoreSweeper < ActionController::Caching::Sweeper
# This sweeper is going to keep an eye on the Product model
observe Product
# If our sweeper detects that a Product was created call this
def after_create(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
private
def expire_cache_for(record)
# Expire the list page now that we added a new product
expire_page(:controller => '#{record}', :action => 'list')
# Expire a fragment
expire_fragment(:controller => '#{record}',
:action => 'recent', :action_suffix => 'all_products')
end
end
需要将清除器添加到将使用它的控制器中。因此,如果我们想在调用创建操作时过期列表和编辑操作的缓存内容,我们可以执行以下操作:
class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
caches_page :list
caches_action :edit
cache_sweeper :store_sweeper, :only => [ :create ]
def list; end
def create
expire_page :action => :list
expire_action :action => :edit
end
def edit; end
end
源Rails指南