#212 Refactoring & Dynamic Delegator
Learn how to refactor a set of conditional Active Record queries using a Dynamic Delegator.
- Download:
- source codeProject Files in Zip (102 KB)
- mp4Full Size H.264 Video (11.9 MB)
- m4vSmaller H.264 Video (8.19 MB)
- webmFull Size VP8 Video (21.1 MB)
- ogvFull Size Theora Video (17.1 MB)
Resources
- Searchlogic (an alternative solution)
- Full episode source code
rails console
Product.search({}).class
Object.instance_methods
BasicObject.instance_methods
Product.search({}).class Object.instance_methods BasicObject.instance_methods
products_controller.rb
@products = Product.search(params)
@products = Product.search(params)
models/product.rb
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
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
lib/dynamic_delegator.rb
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 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

