jordi/xml-object — Issue #4: Feature request: Better handling of collections
Author: mattheworiordan
Created: 2011-11-09 16:26:59+00:00
State: open

I love XML Object, but it's making me write some ugly code to get around some simple issues with the library relating to how it deals with collections.

Take the following simple XML file as an example:

I would naturally expect the following to be true:
`house.walls.length.should == 1`
However this fails as length == 0. Unless there is more than one wall XML node inside walls, the only way to access wall is as follows:
`house.walls.wall`
Surely if a node contains other nodes, it should return length being the number of nodes within it even if there is only one.

When I try the following:
`house.walls.wall.windows.length.should == 3`
it passes and this functionality is as expected

Because of this issue above, I have to write some silly code each time I work with collections as follows to generate a reliable array (0..x) of walls:

walls = if house.walls.respond_to? :each
house.walls
elsif house.walls.respond_to? :wall
[house.wall]
else
[]
end

Would it not be possible to detect how many child objects with the same name are in that node, and even if there is only one or zero, return an array and a correct length?

Also, aside from all of this, there is not a graceful way to detect if an attribute or node exists. It would be useful if there was a way to do something like house.has_garden? to check if one or more garden node exists somehow?

Thanks, and do shout if you think I can help with any of this. I took a quick look through the Gem and to be honest it was quite difficult to understand how it worked, so I've not submitted a pull request for this functionality.

Matt