Here's an annoyance I've run into before, and a simple patch to fix it. Say I want to export some data as xml. I should be able to fire up a script or rake task with my environment, grab some data, then render an rxml template. However, ActionView::Base makes the assumption that I have a controller somewhere and sets tries to set content type headers on it.

The only workaround I've found to date is to create a TestRequest and TestResponse, build an action that loads the data I want and renders with the template I want, expose the action through a real controller, then call the TestRequest and scrape the body of the TestResponse. It works, but it feels....wrong.

This patch skips setting content-type header if there is no controller object, and allows for "standalone" ActionView? use like so:

contacts = Contact.find(:all)
builder = ActionView::Base.new
xml = builder.render( :inline => File.open('template.rxml').read,
                      :type => :rxml,
                      :locals => { :contacts => contacts } )
...
This isn't limited to rxml, obviously -- you can use ERb templates for other data formats.

I've opened this as a ticket: http://dev.rubyonrails.org/ticket/5496

Patch follows and is attached to the ticket.

Thanks!

Solomon



------------------------------------------------------------------------ ----------------------------

Index: vendor/rails/actionpack/lib/action_view/base.rb
===================================================================
--- vendor/rails/actionpack/lib/action_view/base.rb     (revision 4450)
+++ vendor/rails/actionpack/lib/action_view/base.rb     (working copy)
@@ -438,10 +438,10 @@
           body = case extension.to_sym
             when :rxml
               "xml = Builder::XmlMarkup.new(:indent => 2)\n" +
- "@controller.headers['Content-Type'] ||= 'application/ xml'\n" + + (@controller.nil? ? "" : "@controller.headers['Content- Type'] ||= 'application/xml'\n") +
               template
             when :rjs
- "@controller.headers['Content-Type'] ||= 'text/ javascript'\n" + + (@controller.nil? ? "" : "@controller.headers['Content- Type'] ||= 'text/javascript'\n") +
               "update_page do |page|\n#{template}\nend"
           end
         else
_______________________________________________
Rails-core mailing list
Rails-core@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails-core

Reply via email to