Array Properties accept hash with ordered keys and raise error for anything else

This commit is contained in:
Sam Lown 2010-06-18 01:24:49 +02:00
parent dd55466764
commit 1b89f1e1df
7 changed files with 82 additions and 10 deletions

View file

@ -75,6 +75,9 @@ module CouchRest
#
# Addtional options match those of the the belongs_to method.
#
# NOTE: This method is *not* recommended for large collections or collections that change
# frequently! Use with prudence.
#
def collection_of(attrib, *options)
opts = {
:foreign_key => attrib.to_s.singularize + '_ids',
@ -153,7 +156,6 @@ module CouchRest
EOS
end
end
end
@ -168,9 +170,9 @@ module CouchRest
def initialize(array, casted_by, property)
self.property = property
self.casted_by = casted_by
array ||= []
(array ||= []).compact!
casted_by[property.to_s] = [] # replace the original array!
array.each do |obj|
array.compact.each do |obj|
casted_by[property.to_s] << obj.id
end
super(array)

View file

@ -28,8 +28,18 @@ module CouchRest
def cast(parent, value)
return value unless casted
if type.is_a?(Array)
# Convert to array if it is not already
value = [value].compact unless value.is_a?(Array)
if value.nil?
value = []
elsif [Hash, HashWithIndifferentAccess].include?(value.class)
# Assume provided as a Hash where key is index!
data = value
value = [ ]
data.keys.sort.each do |k|
value << data[k]
end
elsif value.class != Array
raise "Expecting an array or keyed hash for property #{parent.class.name}##{self.name}"
end
arr = value.collect { |data| cast_value(parent, data) }
# allow casted_by calls to be passed up chain by wrapping in CastedArray
value = type_class != String ? ::CouchRest::CastedArray.new(arr, self) : arr