【问题标题】:in Rails where do you put your Sweepers?在 Rails 中,您将 Sweepers 放在哪里?
【发布时间】:2012-01-26 19:21:18
【问题描述】:

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

更新:由于观察员被放入app/models,我假设清扫器没有什么不同,只要名称始终以“清扫器”结尾。

【问题讨论】:

  • 只是让你知道,并且与我的回答相关,观察者不需要继续应用程序/模型。
  • 对,我想这纯粹是关于标准的。没有依赖它的功能。

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


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

    扫地机

    缓存清除是一种机制,可让您绕过代码中的大量 expire_{page,action,fragment} 调用。它通过将使缓存内容过期所需的所有工作移至 na ActionController::Caching::Sweeper 类。此类是一个观察者,它通过回调查找对象的更改,当发生更改时,它会使与该对象关联的缓存在周围或后过滤器中过期。

    继续我们的产品控制器示例,我们可以像这样使用清扫器重写它:

    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
    

    源导轨指南

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多