Add with option to decorates_association to allow the decoration to be decorated by a specific association

This commit is contained in:
Michael Fairley 2011-12-17 13:47:59 -08:00
parent 7b6cd2634d
commit 22461fd7c1
3 changed files with 17 additions and 3 deletions

View File

@ -57,12 +57,17 @@ module Draper
# the assocation to be decorated when it is retrieved.
#
# @param [Symbol] name of association to decorate, like `:products`
def self.decorates_association(association_symbol)
# @option opts [Class] :with The decorator to decorate the association with
def self.decorates_association(association_symbol, options = {})
define_method(association_symbol) do
orig_association = model.send(association_symbol)
return orig_association if orig_association.nil?
reflection = model.class.reflect_on_association(association_symbol)
"#{reflection.klass}Decorator".constantize.decorate(orig_association)
if options[:with]
options[:with].decorate(orig_association)
else
reflection = model.class.reflect_on_association(association_symbol)
"#{reflection.klass}Decorator".constantize.decorate(orig_association)
end
end
end

View File

@ -93,6 +93,13 @@ describe Draper::Base do
subject.previous_version.should be_nil
end
end
context "with a specific decorator specified" do
before(:each){ subject.class_eval{ decorates_association :previous_version, :with => SpecificProductDecorator } }
it "causes the association to be decorated with the specified association" do
subject.previous_version.should be_instance_of(SpecificProductDecorator)
end
end
end
context('.decorates_associations') do

View File

@ -0,0 +1,2 @@
class SpecificProductDecorator < ProductDecorator
end