Ruby ROXML - how to get an array to render its xml?
Posted
by Brian D.
on Stack Overflow
See other posts from Stack Overflow
or by Brian D.
Published on 2010-05-16T14:29:28Z
Indexed on
2010/05/17
0:50 UTC
Read the original article
Hit count: 304
I'm trying to create a Messages object that inherits Array. The messages will gather a group of Message objects. I'm trying to create an xml output with ROXML that looks like this:
<messages>
<message>
<type></type>
<code></code>
<body></body>
</message>
...
</messages>
However, I can't figure out how to get the message objects in the Messages object to display in the xml. Here is the code I've been working with:
require 'roxml'
class Message
include ROXML
xml_accessor :type
xml_accessor :code
xml_accessor :body
end
class Messages < Array
include ROXML
# I think this is the problem - but how do I tell ROXML that
# the messages are in this instance of array?
xml_accessor :messages, :as => [Message]
def add(message)
self << message
end
end
message = Message.new
message.type = "error"
message.code = "1234"
message.body = "This is a test message."
messages = Messages.new
messages.add message
puts messages.length
puts messages.to_xml
This outputs:
1
<messages/>
So, the message object I added to messages isn't getting displayed. Anyone have any ideas? Or am I going about this the wrong way?
Thanks for any help.
© Stack Overflow or respective owner