Aggro Nerd


3
Aug/09
0

Ruby on Rails: Rendering Views Outside of the Controller

While working on a CRM system in Ruby on Rails 2.2 I needed to find a way to email one of the users a weekly report. The report would be generated from the PDF templates already integrated with the front-end using the RTex plug-in for Rails. The solution was to include the following in an ActionMailer model to render the view away from the controller and attach the result to an email.

Firstly, create an instance of the ActionView::Base class:

av = ActionView::Base.new(Rails::Configuration.new.view_path)

The next step is to call render which will return the output of the template. In this case the output will be LaTeX because it's a RTeX view:

latex = av.render(:file => "app/views/people/index.pdf.rtex",
    :locals => {:people => people, :current_user => user},
    :layout => "app/views/layouts/standard_landscape.pdf.rtex")

The arguments specify the layout to use and the local variables that are to be passed to the view.

If you're using partials you need to specify explicitly the file extension of the partial (eg. "render :partial => 'addresses/address.pdf.rtex'"). This is because there is no 'request' established for ActionView to ascertain which one to use and it defaults (most likely HTML).

Finally, if you're using RTeX you need to render the LaTeX code to create the PDF file, which you can then attach to an ActionMailer object or save to the file system.

pdf = RTeX::Document.new(latex).to_pdf
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

No trackbacks yet.