2010-03-31 10:25:33 +02:00
|
|
|
#
|
|
|
|
# Wrapper around Array so that the casted_by attribute is set in all
|
|
|
|
# elements of the array.
|
|
|
|
#
|
|
|
|
|
2010-06-20 22:01:11 +02:00
|
|
|
module CouchRest::Model
|
2010-03-31 10:25:33 +02:00
|
|
|
class CastedArray < Array
|
2011-04-20 16:44:49 +02:00
|
|
|
include CouchRest::Model::CastedBy
|
2011-02-28 16:00:41 +01:00
|
|
|
include CouchRest::Model::Dirty
|
2011-04-20 16:44:49 +02:00
|
|
|
attr_accessor :casted_by_property
|
2010-06-16 21:04:53 +02:00
|
|
|
|
2011-04-20 16:44:49 +02:00
|
|
|
def initialize(array, property, parent = nil)
|
|
|
|
self.casted_by_property = property
|
|
|
|
self.casted_by = parent unless parent.nil?
|
2010-06-16 21:04:53 +02:00
|
|
|
super(array)
|
|
|
|
end
|
2011-04-20 16:44:49 +02:00
|
|
|
|
|
|
|
# Adding new entries
|
|
|
|
|
2010-03-31 10:25:33 +02:00
|
|
|
def << obj
|
2010-06-16 21:04:53 +02:00
|
|
|
super(instantiate_and_cast(obj))
|
2010-03-31 10:25:33 +02:00
|
|
|
end
|
2011-04-20 16:44:49 +02:00
|
|
|
|
2010-03-31 10:25:33 +02:00
|
|
|
def push(obj)
|
2010-06-16 21:04:53 +02:00
|
|
|
super(instantiate_and_cast(obj))
|
2010-03-31 10:25:33 +02:00
|
|
|
end
|
2011-02-28 16:00:41 +01:00
|
|
|
|
2011-04-20 16:44:49 +02:00
|
|
|
def unshift(obj)
|
|
|
|
super(instantiate_and_cast(obj))
|
|
|
|
end
|
|
|
|
|
|
|
|
def []= index, obj
|
|
|
|
value = instantiate_and_cast(obj, false)
|
|
|
|
couchrest_parent_will_change! if use_dirty? && value != self[index]
|
|
|
|
super(index, value)
|
|
|
|
end
|
|
|
|
|
2011-02-28 16:00:41 +01:00
|
|
|
def pop
|
2011-03-03 13:52:19 +01:00
|
|
|
couchrest_parent_will_change! if use_dirty? && self.length > 0
|
2011-02-28 16:00:41 +01:00
|
|
|
super
|
|
|
|
end
|
|
|
|
|
|
|
|
def shift
|
2011-03-03 13:52:19 +01:00
|
|
|
couchrest_parent_will_change! if use_dirty? && self.length > 0
|
2011-02-28 16:00:41 +01:00
|
|
|
super
|
|
|
|
end
|
|
|
|
|
2011-03-03 13:52:19 +01:00
|
|
|
def clear
|
|
|
|
couchrest_parent_will_change! if use_dirty? && self.length > 0
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
2011-05-21 14:16:39 +02:00
|
|
|
def build(*args)
|
|
|
|
obj = casted_by_property.build(*args)
|
|
|
|
self.push(obj)
|
|
|
|
obj
|
|
|
|
end
|
|
|
|
|
2010-06-16 21:04:53 +02:00
|
|
|
protected
|
|
|
|
|
2011-04-20 16:44:49 +02:00
|
|
|
def instantiate_and_cast(obj, change = true)
|
|
|
|
property = casted_by_property
|
|
|
|
couchrest_parent_will_change! if change && use_dirty?
|
|
|
|
if casted_by && property && obj.class != property.type_class
|
|
|
|
property.cast_value(casted_by, obj)
|
2010-06-16 21:04:53 +02:00
|
|
|
else
|
2011-04-20 16:44:49 +02:00
|
|
|
obj.casted_by = casted_by if obj.respond_to?(:casted_by)
|
|
|
|
obj.casted_by_property = casted_by_property if obj.respond_to?(:casted_by_property)
|
2010-06-16 21:04:53 +02:00
|
|
|
obj
|
|
|
|
end
|
2010-03-31 10:25:33 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|