在Rails你把扫地车放在哪里?

时间:2012-01-26 19:21:18

标签: ruby-on-rails convention convention-over-configur

Rails中是否存在将Sweeper类放在特定目录位置的约定?

更新:由于观察员被放入app/models,我认为清扫工具没有什么不同,只要名称总是以“清扫工”结束。

3 个答案:

答案 0 :(得分:3)

我喜欢将它们放在 app / sweepers 目录中。

我还将Presenters放在应用程序/演示者目录中......并在 app / observers 目录中放置Observers

答案 1 :(得分:1)

清扫器

缓存清除是一种机制,它使您可以在代码中进行大量的expire_ {page,action,fragment}调用。它通过将使缓存内容过期所需的所有工作移动到 无ActionController :: Caching :: Sweeper类。此类是一个Observer,它通过回调查找对象的更改,并且当发生更改时,它会在过滤器前后或之后终止与该对象关联的缓存。

继续我们的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

必须将清除程序添加到将使用该清除程序的控制器中。因此,如果要在调用create操作时使列表的缓存内容过期并编辑操作,可以执行以下操作:

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

源轨指南

答案 2 :(得分:0)

尝试将它们放在app/models目录中。