From 67c7125192740a7586a3a635acd735ae01b97837 Mon Sep 17 00:00:00 2001 From: stevenbristol Date: Wed, 29 Aug 2012 17:13:23 -0400 Subject: [PATCH] Adds the ability to decorate an enumerable proxy --- lib/draper/decorated_enumerable_proxy.rb | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/draper/decorated_enumerable_proxy.rb b/lib/draper/decorated_enumerable_proxy.rb index fc123c8..4db271c 100644 --- a/lib/draper/decorated_enumerable_proxy.rb +++ b/lib/draper/decorated_enumerable_proxy.rb @@ -4,6 +4,24 @@ module Draper include Enumerable delegate :as_json, :collect, :map, :each, :[], :all?, :include?, :first, :last, :shift, :to => :decorated_collection + + + + # Initialize a new collection decorator instance by passing in + # an instance of a collection. Pass in an optional + # context into the options hash is stored for later use. + # + # + # @param [Object] instances to wrap + # @param [Hash] options (optional) + # @option options [Class] :klass The decorator class to use + # for each item in the collection. + # @option options all other options are passed to Decorator + # class for each item. + + def self.decorate(collection, options = {}) + new( collection, discern_class_from_my_class(options.delete(:klass)), options) + end def initialize(collection, klass, options = {}) @wrapped_collection, @klass, @options = collection, klass, options @@ -70,5 +88,15 @@ module Draper @wrapped_collection end alias_method :to_source, :source + + + private + def self.discern_class_from_my_class default_class + return default_class if default_class + name = InvoiceDecorator.to_s.gsub("Decorator", "") + "#{name.singularize}Decorator".constantize + rescue NameError + raise NameError("You must supply a class (as the klass option) for the members of your collection or the class must be inferable from the name of this class ('#{new.class}')") + end end end