Search code examples
ruby-on-railsrubyrender-to-string

Loading a page into memory in Rails


My rails app produces XML when I load /reports/generate_report.

On a separate page, I want to read this XML into a variable and save it to the database.

How can I do this? Can I somehow stream the response from the /reports/generate_report.xml URI into a variable? Or is there a better way to do it since the XML is produced by the same web app?

Here is my generate_report action:

class ReportsController < ApplicationController
  def generate_report
    respond_to do |format|
      @products = Product.all
      format.xml { render :layout => false }
    end
  end
end

Here is the action I am trying to write:

class AnotherController < ApplicationController
  def archive_current
    @output = # get XML output produced by /reports/generate_report
    # save @output to the database

    respond_to do |format|
      format.html # inform the user of success or failure
    end
  end
end

Solved: My solution (thanks to Mladen Jablanović):

@output = render_to_string(:file => 'reports/generate_report.xml.builder')

I used the following code in a model class to accomplish the same task since render_to_string is (idiotically) a protected method of ActionController::Base:

av = ActionView::Base.new(Rails::Configuration.new.view_path)
@output = av.render(:file => "reports/generate_report.xml.builder")

Solution

  • Perhaps you could extract your XML rendering logic to a separate method within the same controller (probably a private one), which would render the XML to a string using render_to_string, and call it both from generate_report and archive_current actions.