ActiveRecord to_xml not calling to_xml on custom class


#1

I’m using the GeoRuby and Spatial Adapter to do some postgis stuff with
rails. Working great. The thing is, these define custom types that get
stored on these activerecord objects. Things like
GeoRuby::SimpleFeatures::Point. So when I call to_xml everything is
peachy except for that datatype.

0.0 Temperate Canada 11.0 0.0 # 2 -1.0 Ecological reserve

So what I did was define to_json and to_xml methods for these types.
They work fine.

BiologicalMetric.find(:first).geometry.to_xml
=>

<?xml version="1.0" encoding="UTF-8"?> -123.333297729 49.0

So I thought that this would solve all my problems and even be something
I could contribute to the georuby library. Very DRY eh? Wrong!!!
ActiveRecord doesn’t seem to call the to_xml method on these datatypes.
It just does it’s own thing. The JSON serialization ignores the custom
methods as well.

Am I missing something? Why wouldn’t to_xml/to_json be called when the
parent object’s to_xml/to_json method is called?

Thanks,
Chad B.


#2

On Jun 1 2007, 6:51 pm, Chad B. removed_email_address@domain.invalid
wrote:
[…]

Am I missing something? Why wouldn’t to_xml/to_json be called when the
parent object’sto_xml/to_json method is called?

1.5 years later I’m experiencing this problem. I found out that as
opposed to ActiveRecord, ActiveResource uses Hash#to_xml. Hash#to_xml
is in fact written properly, calling to_xml of each value if method
found. ActiveRecord however uses XmlSerializer’s logic which in turn
asks for #to_s instead of #to_xml from each attribute. You’d think “I
can just alias to_s to_xml in my class”, but no. XmlSerializer escapes
whatever it reads from to_s.

Why? Is XmlSerializer broken?