Starter Step

Rendering views in rake tasks

Posted on: May 23, 2009

Recently, I needed to create a background process to offload a long export process. The easiest approach was to just utilize a rake task that would be kicked off by the system command. I ran into an issue because I needed to capture the rendering of a view to create the export file. This is an example of the code that came out of the exploration:

  task :run_export => :environment do
    av =
    av.class_eval do
      include ApplicationHelper
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    file_name = "export_"
    10.times { file_name << chars&#91;rand(chars.size-1)&#93; }

    data = av.render(:partial => "shared/export", :locals => {:surveys => Survey.all})
    FileUtils.mkdir_p "#{RAILS_ROOT}/public/system/exports}""#{RAILS_ROOT}/public/system/exports/#{file_name}.xls", 'w') {|f| f.write(data) }

The above rake task will create an instance of ActionView so that we can call render. My partial also needed access to some helpers I have defined in my ApplicationHelper, so it gets included. Next we generate a psuedo random file name for our export. Then we create a directory for our export files. The directory and its parents are only created if they do not exist. Lastly, we write the result of our render to our file.

Not sure if this is the best approach to this..but seems to work for me.


3 Responses to "Rendering views in rake tasks"

Hey, I have a similar problem, thanks for your post as this would surely help me.

Is it possible to call the controller’s action to do the render stuff?

Thanks in advance!

[…] found various blog posts describing how to render views in a rake task, render a view to a string, etc., but none of them was working for me.  They were all using […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


  • Dave: I can tell you're a ruby guy because you forgot the 'return' keyword. Thanks for the tip though!
  • Chandrashekhar H M: Hi, Thanks its working fine in iOS 6 but not in iOS 7.0. Any Suggestion on this.
  • Coeur: To change a rootViewController, without all this TVNavigationController : myNewRoot = [[UIViewController alloc] init]; myNavigationController.view
%d bloggers like this: