class and Hash.from_xml

I have some xml that looks like this:

<accounts>     <account>        <name>Smith</name>    </account>    <account>       <name>Jones</name> </account> </accounts>

In this case,

acct_hash = Hash.from_xml

produces

acct_hash['accounts']['account']

which is an Array. But if there is only one account in the xml, as in

<accounts>     <account>        <name>Smith</name>    </account> </accounts>

then acct_hash['accounts']['account'] is a Hash.

So to turn those into Account objects I have to do slightly different things depending on the number of accounts. To figure out what to do I'm using

if acct_hash['accounts']['account'].class.to_s == "Array" ...

which works, but seems 'wrong.' Is there a better way? I wonder why Hash.from_xml doesn't just always create an Array. I'm sure there's a good reason, but it would be simpler in this case.

Thanks, -George

Yep, that’s annoying and wrong, but it was fixed months ago in edge: http://dev.rubyonrails.org/changeset/7074

If you upgrade to edge or Rails 2.0 RC1, things will work as you want.

Thanks John. Upgrading isn’t an option right now, but the way I wrote it, it turns out, should work in either case.

Note that you need the type=“array” attribute in the array entity, like so:

Smith

I’m getting the xml by doing a accts = Account.find(:all…), then accts.to_xml.

So Array.to_xml is not adding that type=“array” part. I guess that’s also in edge.

-George

I see you were the one who filed the ticket. btw, don’t know why I wrote John instead of Josh earlier, I wasn’t thinking it, it just came out :slight_smile: