From abb96e564fb45f8ad4e642185cc567e585857901 Mon Sep 17 00:00:00 2001 From: Mario Uher Date: Sat, 28 Jan 2012 00:01:01 +0100 Subject: [PATCH] Added support for :class_name option to mimic the behavior of ActiveRecord and help to unify code. :class / :class_name can now be strings too! --- lib/draper/base.rb | 3 ++- spec/draper/base_spec.rb | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lib/draper/base.rb b/lib/draper/base.rb index 047dbcc..0456572 100644 --- a/lib/draper/base.rb +++ b/lib/draper/base.rb @@ -48,7 +48,8 @@ module Draper # # @param [Symbol] class_name snakecase name of the decorated class, like `:product` def self.decorates(input, options = {}) - self.model_class = options[:class] || input.to_s.camelize.constantize + self.model_class = options[:class] || options[:class_name] || input.to_s.camelize + self.model_class = model_class.constantize if model_class.respond_to?(:constantize) model_class.send :include, Draper::ModelSupport define_method(input){ @model } end diff --git a/spec/draper/base_spec.rb b/spec/draper/base_spec.rb index 67f0248..8aaff2c 100644 --- a/spec/draper/base_spec.rb +++ b/spec/draper/base_spec.rb @@ -53,6 +53,44 @@ describe Draper::Base do BusinessDecorator.model_class.should == Business end.should_not raise_error end + + context("accepts ActiveRecord like :class_name option too") do + it "accepts constants for :class" do + expect do + class CustomDecorator < Draper::Base + decorates :product, :class => Product + end + CustomDecorator.model_class.should == Product + end.should_not raise_error + end + + it "accepts constants for :class_name" do + expect do + class CustomDecorator < Draper::Base + decorates :product, :class_name => Product + end + CustomDecorator.model_class.should == Product + end.should_not raise_error + end + + it "accepts strings for :class" do + expect do + class CustomDecorator < Draper::Base + decorates :product, :class => 'Product' + end + CustomDecorator.model_class.should == Product + end.should_not raise_error + end + + it "accepts strings for :class_name" do + expect do + class CustomDecorator < Draper::Base + decorates :product, :class_name => 'Product' + end + CustomDecorator.model_class.should == Product + end.should_not raise_error + end + end it "creates a named accessor for the wrapped model" do pd = ProductDecorator.new(source)