原文: http://railscasts.com/episodes/212-refactoring-dynamic-delegator?autoplay=true
代码从:
class Product < ActiveRecord::Base
belongs_to :category
def self.search(params)
products = scoped
products = products.where("name like ?", "%" + params[:name] + "%") if params[:name]
products = products.where("price >= ?", params[:price_gt]) if params[:price_gt]
products = products.where("price <= ?", params[:price_lt]) if params[:price_lt]
products
end
end
换成:
class DynamicDelegator < BasicObject
def initialize(target)
@target = target
end
def method_missing(*args, &block)
result = @target.send(*args, &block)
@target = result if result.kind_of? @target.class
result
end
end
class Product < ActiveRecord::Base
belongs_to :category
def self.search(params)
products = scope_builder
products.where("name like ?", "%" + params[:name] + "%") if params[:name]
products.where("price >= ?", params[:price_gt]) if params[:price_gt]
products.where("price <= ?", params[:price_lt]) if params[:price_lt]
products
end
def self.scope_builder
DynamicDelegator.new(scoped)
end
end
请教这是为什么这样改,英语不太好,看了好几遍视频和文档都搞不懂本质是为什么要这样做?