我正在努力改进这个mixin,但困扰我的一件事是,我似乎无法让模块的其他部分了解self.included(base)中的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
在included
方法中没有自动注册的魔力,我只需要向initialize_scopes
这样的模块添加一个initializaton方法,并从使用该模块扩展类的位置调用
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, ...