Create decorators with context

This commit is contained in:
Les Hill 2011-08-08 18:01:31 -07:00
parent 7412475891
commit cad25f7a8d
2 changed files with 36 additions and 13 deletions

View File

@ -2,16 +2,17 @@ module Draper
class Base
require 'active_support/core_ext/class/attribute'
class_attribute :denied, :allowed, :model_class
attr_accessor :model
attr_accessor :context, :model
DEFAULT_DENIED = Object.new.methods << :method_missing
FORCED_PROXY = [:to_param]
self.denied = DEFAULT_DENIED
def initialize(input)
def initialize(input, context = nil)
input.inspect
self.class.model_class = input.class if model_class.nil?
@model = input
self.context = context
build_methods
end
@ -35,8 +36,8 @@ module Draper
self.allowed = input_allows
end
def self.decorate(input)
input.respond_to?(:each) ? input.map{|i| new(i)} : new(input)
def self.decorate(input, context = nil)
input.respond_to?(:each) ? input.map{|i| new(i, context)} : new(input, context)
end
def helpers

View File

@ -75,22 +75,44 @@ describe Draper::Base do
end
context ".decorate" do
subject { Draper::Base.decorate(source) }
context "without any context" do
subject { Draper::Base.decorate(source) }
context "when given a collection of source objects" do
let(:source) { [Product.new, Product.new] }
context "when given a collection of source objects" do
let(:source) { [Product.new, Product.new] }
its(:size) { should == source.size }
its(:size) { should == source.size }
it "returns a collection of wrapped objects" do
subject.each{ |decorated| decorated.should be_instance_of(Draper::Base) }
it "returns a collection of wrapped objects" do
subject.each{ |decorated| decorated.should be_instance_of(Draper::Base) }
end
end
context "when given a single source object" do
let(:source) { Product.new }
it { should be_instance_of(Draper::Base) }
end
end
context "when given a single source object" do
let(:source) { Product.new }
context "with a context" do
let(:context) {{ :some => 'data' }}
it { should be_instance_of(Draper::Base) }
subject { Draper::Base.decorate(source, context) }
context "when given a collection of source objects" do
let(:source) { [Product.new, Product.new] }
it "returns a collection of wrapped objects with the context" do
subject.each{ |decorated| decorated.context.should eq(context) }
end
end
context "when given a single source object" do
let(:source) { Product.new }
its(:context) { should eq(context) }
end
end
end