Fixing assiging hashes to casted arrays properties

This commit is contained in:
Sam Lown 2011-06-08 19:14:01 +02:00
parent 7e054fd948
commit ea4325f5bf
3 changed files with 16 additions and 12 deletions

View file

@ -1 +1 @@
1.1.0.rc
1.1.0.rc1

View file

@ -26,13 +26,9 @@ module CouchRest::Model
if type.is_a?(Array)
if value.nil?
value = []
elsif value.is_a?(Hash)
# Assume provided as a Hash where key is index!
data = value
value = [ ]
data.keys.sort.each do |k|
value << data[k]
end
elsif [Hash, HashWithIndifferentAccess].include?(value.class)
# Assume provided as a params hash where key is index
value = parameter_hash_to_array(value)
elsif !value.is_a?(Array)
raise "Expecting an array or keyed hash for property #{parent.class.name}##{self.name}"
end
@ -78,6 +74,14 @@ module CouchRest::Model
private
def parameter_hash_to_array(source)
value = [ ]
source.keys.each do |k|
value[k.to_i] = source[k]
end
value.compact
end
def associate_casted_value_to_parent(parent, value)
value.casted_by = parent if value.respond_to?(:casted_by)
value.casted_by_property = self if value.respond_to?(:casted_by_property)

View file

@ -276,9 +276,9 @@ describe "properties of array of casted models" do
end
it "should allow attribute to be set from hash with ordered keys and sub-hashes" do
@course.questions = { '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} }
@course.questions.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions = { '10' => {:q => 'Test10'}, '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} }
@course.questions.length.should eql(3)
@course.questions.last.q.should eql('Test10')
@course.questions.last.class.should eql(Question)
end
@ -295,7 +295,7 @@ describe "properties of array of casted models" do
it "should raise an error if attempting to set single value for array type" do
lambda {
@course.questions = Question.new(:q => 'test1')
}.should raise_error
}.should raise_error(/Expecting an array/)
end