@@ -130,6 +130,7 @@ def initialize(object, options={})
130
130
@object = object
131
131
@scope = options [ :scope ]
132
132
@root = options . fetch ( :root , self . class . _root )
133
+ @polymorphic = options . fetch ( :polymorphic , false )
133
134
@meta_key = options [ :meta_key ] || :meta
134
135
@meta = options [ @meta_key ]
135
136
@wrap_in_array = options [ :_wrap_in_array ]
@@ -138,7 +139,7 @@ def initialize(object, options={})
138
139
@key_format = options [ :key_format ]
139
140
@context = options [ :context ]
140
141
end
141
- attr_accessor :object , :scope , :root , :meta_key , :meta , :key_format , :context
142
+ attr_accessor :object , :scope , :root , :meta_key , :meta , :key_format , :context , :polymorphic
142
143
143
144
def json_key
144
145
key = if root == true || root . nil?
@@ -225,9 +226,9 @@ def serialize(association)
225
226
def serialize_ids ( association )
226
227
associated_data = send ( association . name )
227
228
if associated_data . respond_to? ( :to_ary )
228
- associated_data . map { |elem | elem . read_attribute_for_serialization ( association . embed_key ) }
229
+ associated_data . map { |elem | serialize_id ( elem , association ) }
229
230
else
230
- associated_data . read_attribute_for_serialization ( association . embed_key ) if associated_data
231
+ serialize_id ( associated_data , association ) if associated_data
231
232
end
232
233
end
233
234
@@ -260,9 +261,19 @@ def serializable_object(options={})
260
261
hash = attributes
261
262
hash . merge! associations
262
263
hash = convert_keys ( hash ) if key_format . present?
264
+ hash = { :type => type_name ( @object ) , type_name ( @object ) => hash } if @polymorphic
263
265
@wrap_in_array ? [ hash ] : hash
264
266
end
265
267
alias_method :serializable_hash , :serializable_object
268
+
269
+ def serialize_id ( elem , association )
270
+ id = elem . read_attribute_for_serialization ( association . embed_key )
271
+ association . polymorphic? ? { id : id , type : type_name ( elem ) } : id
272
+ end
273
+
274
+ def type_name ( elem )
275
+ elem . class . to_s . demodulize . underscore . to_sym
276
+ end
266
277
end
267
278
268
279
end
0 commit comments