代码之家  ›  专栏  ›  技术社区  ›  Adam Lassek

保持命名范围扩展干燥

  •  2
  • Adam Lassek  · 技术社区  · 16 年前

    在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 对象。

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

    2 回复  |  直到 11 年前
        1
  •  2
  •   Alex Reisner    16 年前

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

    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 方法。

        2
  •  0
  •   standup75    15 年前

    好得多:

    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)和 include NamedScope 在你 User