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 = ActionView::Base.new(Rails::Configuration.new.view_path)
    av.class_eval do
      include ApplicationHelper
    end
 
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    file_name = "export_"
    10.times { file_name << chars[rand(chars.size-1)] }

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

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.

About these ads

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: