roar
roar copied to clipboard
XML serialization / format output for serialize :attribute, Hash
Hi
I have a model Product with a bunch of serialized attributes - like so. This is a to keep some information that's calculated and updated once a week usually for reporting - and I don't do any searches on this data - it's essentially a free form dump field for stats.
class Product < ActiveRecord::Base
serialize :stock_details, Hash
serialize :stats, Hash
end
Anyways when I render this as JSON - it's fine, cause hashes are first-class citizens. They are essentially Javascript objects ( for my purposes.)
{
"id": 103323,
"stats": {
"shipped": {
"this_week": 0,
"this_month": 0,
"this_year": 0,
"last_week": 0,
"last_month": 0,
"last_year": 3
},
"ordered": {
"this_week": 0,
"this_month": 0,
"this_year": 0,
"last_week": 0,
"last_month": 0,
"last_year": 7
}
},
}
However see what's happening to the same data when requested as xml. Any ideas what to do here?
<>
<id>103323</id>
<stats>{:shipped=>{:this_week=>0, :this_month=>0, :this_year=>0, :last_week=>0, :last_month=>0, :last_year=>3}, :ordered=>{:this_week=>0, :this_month=>0, :this_year=>0, :last_week=>0, :last_month=>0, :last_year=>7}, :top_customers_by_volume=>{"503012"=>2, "AJRI"=>2, "VOID"=>2, "SSA001"=>1, "215404"=>1, "505886"=>1, "514287"=>1, "167319"=>1}}</stats>
</>
What's the proper way to render this as XML?
You can use the ::hash
property, please check the XML tests. I couldn't find it in the documentation myself, so might have missed to that.
It works like
hash :stats
https://github.com/apotonick/representable/#more-on-xml
Didn't make any difference for XML. But I do have complex hashes and hashes with arrays. I'm going to try implementing a separate representer for XML, thou I was mostly just playing with it - to see if I could get XML out of this setup for free. I don't need to support it now - JSON is what I need for API. I might need to expose XML interface down the line if we try more integrations with legacy systems.
I am pretty sure there's hash support out-of-the-box with Representable, my internet is terribly slow currently but I can try to find an example for you.
@apotonick If you ever found an example it would be very helpful to see it. I was unable to and the hash
syntax you mentioned above didn't seem to do anything for me.
Update: I actually did get this to work, but now I have an additional question. hash
seems to only work one level deep into the XML. I have a hash with multiple levels of nested hashes and the deeper levels are not getting xml-ized.
Here is an example of what it looks like when I use hash :filters
<filters>
<provider>
{"npi"=>"689", "tin"=>"155", "address"=>[{"street"=>["11 Main St"], "city"=>"NewTown", "state"=>"MO", "zip"=>"12345", "country"=>"us"}]}
</provider>
</filters>