Render from your Model

Ok, with MVC anti-purism aside, how can I render an RXML template from
a Model? I have a Model object which I want to serialize to XML. I
originally had all my XML generation methods inside the Model object
itself and that works just fine, but now I want to clean up the object
and I think it would be best to put in an RXML template. But none of
the render() set of methods work from a Model, only
ActionController/ActionView.

Someone has blogged about this before at:
http://blog.yanime.org/articles/2006/08/05/rails-calling-render-outside-your-controllers

But the problem with this approach is that you cannot assign variables
and/or the template does not pick up any instance variables you have
set in your model prior to the render() call.

So does anybody have any ideas? Or should I just go back to the
stone-age and place my XML right in the Model?

thanks
-william

Your best bet is probably to build a generic controller to serialize a
given model to XML. That way you don’t have to break MVC and your code
is nice and clean.

Hi,

Why not just use to_xml() ? ( Rails 1.2 & Edge )

See ActiveRecord::Base
and http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/
Hash/Conversions.html

  • Lourens

Sure you can.

active_record/lib/active_record/xml_serialization.rb

Straight from the docs:

 # To include any methods on the object(s) being called use :methods
 #
 #   firm.to_xml :methods =>

[ :calculated_earnings, :real_earnings ]
#
#
# # … normal attributes as shown above …
# 100000000000000000
# 5
#
#
# To call any Proc’s on the object(s) use :procs. The Proc’s
# are passed a modified version of the options hash that was
# given to #to_xml.
#
# proc = Proc.new { |options| options[:builder].tag!(‘abc’,
‘def’) }
# firm.to_xml :procs => [ proc ]
#
#
# # … normal attributes as shown above …
# def
#
#
# You may override the to_xml method in your ActiveRecord::Base
# subclasses if you need to. The general form of doing this is
#
# class IHaveMyOwnXML < ActiveRecord::Base
# def to_xml(options = {})
# options[:indent] ||= 2
# xml = options[:builder] ||= Builder::XmlMarkup.new
(:indent => options[:indent])
# xml.instruct! unless options[:skip_instruct]
# xml.level_one do
# xml.tag!(:second_level, ‘content’)
# end
# end
# end

I cannot use to_xml() because my XML is not generic enough, its
specific.

I was able to get that one Module to work, that is:

http://blog.yanime.org/articles/2006/08/05/rails-calling-render-outside-your-controllers

Thanks for all your ideas and help!