diff --git a/lib/draper/base.rb b/lib/draper/base.rb index 0abd36c..1dee812 100644 --- a/lib/draper/base.rb +++ b/lib/draper/base.rb @@ -190,9 +190,9 @@ module Draper def method_missing(method, *args, &block) if allow?(method) begin - self.class.send :define_method, method do |*args, &block| + self.class.send :define_method, method do |*args, &block| model.send(method, *args, &block) - end + end self.send(method, *args, &block) rescue NoMethodError super @@ -203,7 +203,11 @@ module Draper end def self.method_missing(method, *args, &block) - model_class.send(method, *args, &block) + if method.to_s.match(/^find_by.*/) + self.decorate(model_class.send(method, *args, &block)) + else + model_class.send(method, *args, &block) + end end def self.respond_to?(method, include_private = false) diff --git a/spec/draper/base_spec.rb b/spec/draper/base_spec.rb index 3670e05..02fcc24 100644 --- a/spec/draper/base_spec.rb +++ b/spec/draper/base_spec.rb @@ -177,6 +177,34 @@ describe Draper::Base do pd.context.should == :admin end end + + context ".find_by_(x)" do + it "runs the similarly named finder" do + Product.should_receive(:find_by_name) + ProductDecorator.find_by_name("apples") + end + + it "returns a decorated result" do + ProductDecorator.find_by_name("apples").should be_kind_of(ProductDecorator) + end + + it "runs complex finders" do + Product.should_receive(:find_by_name_and_size) + ProductDecorator.find_by_name_and_size("apples", "large") + end + + it "accepts an options hash" do + Product.should_receive(:find_by_name_and_size).with("apples", "large", {:role => :admin}) + ProductDecorator.find_by_name_and_size("apples", "large", {:role => :admin}) + end + + it "uses the options hash in the decorator instantiation" do + pending "Figure out an implementation that supports multiple args (find_by_name_and_count_and_size) plus an options hash" + Product.should_receive(:find_by_name_and_size).with("apples", "large", {:role => :admin}) + pd = ProductDecorator.find_by_name_and_size("apples", "large", {:role => :admin}) + pd.context[:role].should == :admin + end + end context ".decorate" do context "without any context" do diff --git a/spec/support/samples/product.rb b/spec/support/samples/product.rb index fe5d371..ca556c3 100644 --- a/spec/support/samples/product.rb +++ b/spec/support/samples/product.rb @@ -1,5 +1,9 @@ class Product < ActiveRecord::Base include Draper::ModelSupport + + def self.find_by_name(name) + @@dummy ||= Product.new + end def self.first @@first ||= Product.new