【问题标题】:Improving this mix in改善这种混合
【发布时间】:2016-07-18 18:16:44
【问题描述】:

我正在尝试改进这个 mixin,而困扰我的一件事是我似乎无法让模块的其余部分了解 self.included(base) 中的基本属性,所以我有将 base 传递给每个模块方法。有没有更好的方法:

module SearchSort
      def self.included(base)
        # binds included class's class methods
        base.send :extend, ClassMethods
        initialize_scopes(base)
      end

      def self.initialize_scopes(base)
        initialize_type_scope(base)
        initialize_product_name_scope(base)
      end

      def self.initialize_type_scope(base)
        base.scope :for_work_type, lambda { |work_type|
        Rails.logger.debug("-----(45) work_type #{work_type}")
        terms = process_terms(work_type)
      base.where(
        terms.map { '(LOWER(workable_type) LIKE ?)' }.join(' AND '),
        *terms.map { |e| [e] * 1 }.flatten)
    }
  end

  def self.initialize_product_name_scope(base)
    base.scope :for_product_name, lambda { |product_name|
      terms = process_terms(product_name)
      base.where(
        terms.map { '(LOWER(products.name) LIKE ?)' }.join(' AND '),
        *terms.map { |e| [e] * 1 }.flatten
      ).joins(:product)
    }
  end

  module ClassMethods
    def pid_opts
      [%w(Newly\ Added newly_added), %w(Waiting waiting),
       %w(Ready ready), %w(Working working),
       %w(Error error), %w('Error Retry', 'error_retry'),
       %w(Done done), %w(Gated gated)
      ]
    end
  end
end

【问题讨论】:

  • 一种替代方法是在初始化阶段添加类级变量以保存base,然后将其删除。就我个人而言,我更喜欢传递参数,就像你已经做的那样。

标签: ruby ruby-on-rails-3 mixins


【解决方案1】:

而不是在included 方法中使用自动注册魔法,我只需向模块添加一个初始化方法,如initialize_scopes 并从使用该模块扩展类的位置调用

extend SearchSort
initialize_scopes

由于使用了extend,模块中定义的方法在类上下文中执行(都是self的上下文)。

举个例子,我将这个模式用于acts_as_api

module ApiHandling
  def expose_api(*fields)
    acts_as_api

    api_accessible :ios_v1 do |template|
      fields.each { |field| template.add field }
    end
  end
end

这样使用:

class Event < ActiveRecord::Base
  extend ApiHandling
  expose_api :id, :name, :description, ...

【讨论】:

    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多