【问题标题】:Keeping named_scope Extensions DRY保持 named_scope 扩展 DRY
【发布时间】:2010-02-04 00:37:47
【问题描述】:

在 Rails 中,您可以在 named_scope 之后添加一个块,用于其他上下文相关的方法,如下所示:

class User < ActiveRecord::Base
  named_scope :inactive, :conditions => {:active => false} do
    def activate
      each { |i| i.update_attribute(:active, true) }
    end
  end
end

在此示例中,activate 方法不是在 User 类上定义的,而是在 ActiveRecord::NamedScope::Scope 对象上定义的。

我有一系列三个范围,它们需要具有相同的方法定义。为了不重复代码,我将如何抽象该块以便我可以定义一次并将其传递给每个named_scope

【问题讨论】:

    标签: ruby-on-rails named-scope


    【解决方案1】:

    首先,很好的问题——我不知道命名范围的那个特性!以下对我有用:

    class User < ActiveRecord::Base
      add_activate = lambda do
        define_method "activate" do
          each { |i| i.update_attribute(:active, true) }
        end
      end
    
      named_scope :inactive, :conditions => {:active => false}, &add_activate
    end
    

    您可以将add_activate 块作为最后一个参数传递给任何需要activate 方法的命名范围。

    【讨论】:

    • 谢谢!我忘记了&amp;。知道这很简单。
    【解决方案2】:

    好多了:

    http://tuxicity.se/rails/dry/2009/01/04/share-named-scopes-in-rails.html

    module NamedScope
      def self.included(base)
        base.class_eval do
          named_scope :inactive, :conditions => {:active => false} do
            def activate
              each { |i| i.update_attribute(:active, true) }
            end
          end
        end
      end
    end
    

    保存在您的 /lib 目录中(在 rails 3 的初始化程序中放入一个 require)和您的 User 类中的 include NamedScope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多