From ea4325f5bf8da0d0113b7cdd6874478480baf24b Mon Sep 17 00:00:00 2001 From: Sam Lown Date: Wed, 8 Jun 2011 19:14:01 +0200 Subject: [PATCH] Fixing assiging hashes to casted arrays properties --- VERSION | 2 +- lib/couchrest/model/property.rb | 18 +++++++++++------- spec/couchrest/property_spec.rb | 8 ++++---- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/VERSION b/VERSION index 0859045..de1d3a8 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.0.rc +1.1.0.rc1 diff --git a/lib/couchrest/model/property.rb b/lib/couchrest/model/property.rb index 07fdfe8..9beb5c7 100644 --- a/lib/couchrest/model/property.rb +++ b/lib/couchrest/model/property.rb @@ -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) diff --git a/spec/couchrest/property_spec.rb b/spec/couchrest/property_spec.rb index 5379269..6da6b3b 100644 --- a/spec/couchrest/property_spec.rb +++ b/spec/couchrest/property_spec.rb @@ -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