Refactor object creating and add pending spec

This commit is contained in:
Dmytrii Nagirniak 2012-09-24 18:08:07 +10:00
parent a581d0a3ec
commit 3f59065366
2 changed files with 25 additions and 9 deletions

View File

@ -92,13 +92,26 @@ module Cocoon
def create_object(f, association) def create_object(f, association)
assoc = f.object.class.reflect_on_association(association) assoc = f.object.class.reflect_on_association(association)
raise "Association #{association} doesn't exist on #{f.object.class}" unless assoc assoc ? create_object_on_association(f, association, assoc) : create_object_on_non_association(f, association)
if assoc.class.name == "Mongoid::Relations::Metadata" end
conditions = assoc.respond_to?(:conditions) ? assoc.conditions.flatten : []
assoc.klass.new(*conditions) 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 else
# assume ActiveRecord or compatible # assume ActiveRecord or compatible
if assoc.collection? if instance.collection?
f.object.send(association).build f.object.send(association).build
else else
f.object.send("build_#{association}") f.object.send("build_#{association}")
@ -106,9 +119,5 @@ module Cocoon
end end
end end
def get_partial_path(partial, association)
partial ? partial : association.to_s.singularize + "_fields"
end
end end
end end

View File

@ -195,6 +195,13 @@ describe Cocoon do
it "should raise error if cannot reflect on association" 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/ expect { @tester.create_object(stub(:object => Comment.new), :not_existing) }.to raise_error /exist/
end 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 end
context "get_partial_path" do context "get_partial_path" do