From 577277b6bd54ab5fbbda3849a02f178589d3f888 Mon Sep 17 00:00:00 2001 From: Jeff Casimir Date: Sat, 23 Jul 2011 08:39:48 -0700 Subject: [PATCH] Added the ability to automatically do lookups by passing an integer ID to .new --- lib/draper/base.rb | 9 ++++++++- spec/base_spec.rb | 16 +++++++++++++++- spec/samples/product_decorator.rb | 9 +++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 spec/samples/product_decorator.rb diff --git a/lib/draper/base.rb b/lib/draper/base.rb index 0afae22..876e646 100644 --- a/lib/draper/base.rb +++ b/lib/draper/base.rb @@ -1,7 +1,7 @@ module Draper class Base require 'active_support/core_ext/class/attribute' - class_attribute :denied, :allowed, :source_class + class_attribute :denied, :allowed, :source_class, :model_class attr_accessor :model DEFAULT_DENIED = Object.new.methods @@ -9,12 +9,19 @@ module Draper self.denied = DEFAULT_DENIED def initialize(input) + if input.instance_of?(Fixnum) + input = model_class.find(Fixnum) + end input.inspect self.class.source_class = input.class @model = input build_methods end + def self.decorates(input) + self.model_class = input.to_s.classify.constantize + end + def self.denies(*input_denied) raise ArgumentError, "Specify at least one method (as a symbol) to exclude when using denies" if input_denied.empty? raise ArgumentError, "Use either 'allows' or 'denies', but not both." if self.allowed? diff --git a/spec/base_spec.rb b/spec/base_spec.rb index 9fc98b0..8c0bbc8 100644 --- a/spec/base_spec.rb +++ b/spec/base_spec.rb @@ -4,7 +4,13 @@ require 'draper' describe Draper::Base do subject{ Draper::Base.new(source) } let(:source){ "Sample String" } - + + context(".decorates") do + it "sets the model class for the decorator" do + ProductDecorator.new(source).model_class == Product + end + end + it "should return the wrapped object when converted to a model" do subject.to_model.should == source end @@ -26,6 +32,14 @@ describe Draper::Base do Draper::Base.new(source).to_param.should == 1 end + context ".new" do + it "should lookup the associated model when passed an integer" do + pd = ProductDecorator.new(1) + pd.should be_instance_of(ProductDecorator) + pd.model.should be_instance_of(Product) + end + end + context ".decorate" do it "should return a collection of wrapped objects when given a collection of source objects" do sources = ["one", "two", "three"] diff --git a/spec/samples/product_decorator.rb b/spec/samples/product_decorator.rb new file mode 100644 index 0000000..fc69334 --- /dev/null +++ b/spec/samples/product_decorator.rb @@ -0,0 +1,9 @@ +class Product + def self.find(id) + return Product.new + end +end + +class ProductDecorator < Draper::Base + decorates :product +end