Forum: Ruby on Rails to_xml and helper methods

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3518ff338e5eee9b32eb1815daabc602?d=identicon&s=25 Marcelo Barbudas (Guest)
on 2008-11-10 16:16
(Received via mailing list)
Hi,

I have an array with objects and I want to generate an XML like:

<objects>
  <object>
       <category_id>1</category_id>
       <helper-method>result 1</helper-method>
  </object>
  <object>
       <category_id>2</category_id>
       <helper-method>result 2</helper-method>
  </object>
</objects>

The helper method generates some urls and it needs as an arguments the
object.

What would be a proper way to include the result of that method call?

I guess building the xml manually could work, but that means I would
have to manually enter every object variable.

--
M.
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2008-11-11 20:51
(Received via mailing list)
modify the to_xml method of your object, like so:

class MyObject < ActiveRecord::Base
  def helper_method(obj)
    "<helper-method>something-from-obj-#{obj.id}</helper-method>"
  end

  def to_xml
    xml = super
    close_tag = "</#{self.class.to_s.underscore.dasherize}>"
    xml.gsub(close_tag, "  #{self.helper_method(self)}\n#{close_tag}")
  end
end
3518ff338e5eee9b32eb1815daabc602?d=identicon&s=25 Marcelo Barbudas (Guest)
on 2008-11-12 15:02
(Received via mailing list)
My problem is that the helper method, is a Helper(app/helpers)
Method. :)

And I can't use it in the model. Otherwise I could have called to_xml
( :method => etc).

--
M.
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2008-11-12 15:14
(Received via mailing list)
In your model, you should just be able to include the helper:

class MyObject < ActiveRecord::Base
  include SomeHelper
end
This topic is locked and can not be replied to.