在Rails中,你应该把你的Sweeper放在哪里?

7

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

更新:由于观察者被放置在app/models中,我认为Sweeper也是一样的,只要名称始终以"sweeper"结尾。


只是让你知道,并且与我的回答相关,观察者不需要进入app/models。 - Gazler
好的,我想这个纯粹是关于标准的问题。没有任何依赖于它的功能。 - m33lky
3个回答

5

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

我还将Presenters放在app/presenters目录中...而将Observers放在app/observers目录中。


5
如果你在Rails中使用Active Record,观察者类通常存储在app/models目录下,并按照app/models/audit_observer.rb的命名规则命名。详见http://api.rubyonrails.org/classes/ActiveRecord/Observer.html。 - m33lky
嗯,如果你生成它们,那就是它们被放置的地方,我一直觉得这是一个不太明显的放置位置。不过还是谢谢你提供的链接。 - Gazler
有没有一个命令标志可以让生成器将文件放在不同的目录中? - m33lky
1
好问题,看起来不是。https://github.com/rails/rails/blob/master/activerecord/lib/rails/generators/active_record/observer/observer_generator.rb - Gazler

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

-2

清除器

缓存清除是一种机制,它允许您在代码中避免大量的 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指南


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接