Added the ability to automatically do lookups by passing an integer ID to .new

This commit is contained in:
Jeff Casimir 2011-07-23 08:39:48 -07:00
parent 9e8f1a3a02
commit 577277b6bd
3 changed files with 32 additions and 2 deletions

View File

@ -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?

View File

@ -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"]

View File

@ -0,0 +1,9 @@
class Product
def self.find(id)
return Product.new
end
end
class ProductDecorator < Draper::Base
decorates :product
end