Adding support for defining cast_as on properties as a Class

This commit is contained in:
Sam Lown 2010-03-30 20:50:47 +00:00
parent 64d68ecc1a
commit dd3df8fb69
8 changed files with 34 additions and 25 deletions

View file

@ -156,4 +156,4 @@ module CouchRest
url
end
end # class << self
end
end

View file

@ -50,24 +50,18 @@ module CouchRest
# Don't cast the property unless it has a value
return unless self[key]
if property.type.is_a?(Array)
klass = ::CouchRest.constantize(property.type[0])
klass = property.type[0]
self[key] = [self[key]] unless self[key].is_a?(Array)
arr = self[key].collect do |value|
value = typecast_value(value, klass, property.init_method)
associate_casted_to_parent(value, assigned)
value
end
# only cast arrays of more complex objects (i.e. not strings)
# allow casted_by calls to be passed up chain by wrapping in CastedArray
self[key] = klass != String ? CastedArray.new(arr) : arr
self[key].casted_by = self if self[key].respond_to?(:casted_by)
else
if property.type.downcase == 'boolean'
klass = TrueClass
else
klass = ::CouchRest.constantize(property.type)
end
self[key] = typecast_value(self[key], klass, property.init_method)
self[key] = typecast_value(self[key], property.type, property.init_method)
associate_casted_to_parent(self[key], assigned)
end
end

View file

@ -16,11 +16,19 @@ module CouchRest
def parse_type(type)
if type.nil?
@type = 'String'
@type = String
elsif type.is_a?(Array) && type.empty?
@type = ['Object']
@type = [Object]
else
@type = type.is_a?(Array) ? [type.first.to_s] : type.to_s
base_type = type.is_a?(Array) ? type.first : type
if base_type.is_a?(String)
base_type = TrueClass if base_type.downcase == 'boolean'
begin
base_type = ::CouchRest.constantize(base_type) unless base_type.is_a?(Class)
rescue # leave base type as is and convert in more/typecast
end
end
@type = type.is_a?(Array) ? [base_type] : base_type
end
end

View file

@ -28,6 +28,7 @@ module CouchRest
def typecast_value(value, klass, init_method)
return nil if value.nil?
klass = ::CouchRest.constantize(klass) unless klass.is_a?(Class)
if value.instance_of?(klass) || klass == Object
value
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)

View file

@ -101,7 +101,7 @@ module CouchRest
end
# length
if property.type == "String"
if property.type == String
# XXX: maybe length should always return a Range, with the min defaulting to 1
# 52 being the max set
len = property.options.fetch(:length, property.options.fetch(:size, 52))