From 3f590653665ba1c3a7fd349e64012987c633fc06 Mon Sep 17 00:00:00 2001 From: Dmytrii Nagirniak Date: Mon, 24 Sep 2012 18:08:07 +1000 Subject: [PATCH] Refactor object creating and add pending spec --- lib/cocoon/view_helpers.rb | 27 ++++++++++++++++++--------- spec/cocoon_spec.rb | 7 +++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/lib/cocoon/view_helpers.rb b/lib/cocoon/view_helpers.rb index 2321894..59e080b 100644 --- a/lib/cocoon/view_helpers.rb +++ b/lib/cocoon/view_helpers.rb @@ -92,13 +92,26 @@ module Cocoon def create_object(f, association) assoc = f.object.class.reflect_on_association(association) - raise "Association #{association} doesn't exist on #{f.object.class}" unless assoc - if assoc.class.name == "Mongoid::Relations::Metadata" - conditions = assoc.respond_to?(:conditions) ? assoc.conditions.flatten : [] - assoc.klass.new(*conditions) + assoc ? create_object_on_association(f, association, assoc) : create_object_on_non_association(f, association) + end + + def get_partial_path(partial, association) + partial ? partial : association.to_s.singularize + "_fields" + end + + private + + def create_object_on_non_association(f, association) + raise "Association #{association} doesn't exist on #{f.object.class}" + end + + def create_object_on_association(f, association, instance) + if instance.class.name == "Mongoid::Relations::Metadata" + conditions = instance.respond_to?(:conditions) ? instance.conditions.flatten : [] + instance.klass.new(*conditions) else # assume ActiveRecord or compatible - if assoc.collection? + if instance.collection? f.object.send(association).build else f.object.send("build_#{association}") @@ -106,9 +119,5 @@ module Cocoon end end - def get_partial_path(partial, association) - partial ? partial : association.to_s.singularize + "_fields" - end - end end diff --git a/spec/cocoon_spec.rb b/spec/cocoon_spec.rb index cc1a61a..57522aa 100644 --- a/spec/cocoon_spec.rb +++ b/spec/cocoon_spec.rb @@ -195,6 +195,13 @@ describe Cocoon do it "should raise error if cannot reflect on association" do expect { @tester.create_object(stub(:object => Comment.new), :not_existing) }.to raise_error /exist/ end + + it "should create an association if object responds to 'build_association' as singular" do + pending 'WIP' + object = Comment.new + object.should_receive(:build_custom_item).and_return 'custom' + @tester.create_object(stub(:object => Comment.new), :custom_item).should == 'custom' + end end context "get_partial_path" do