【发布时间】: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