Posted by: Jake Dempsey 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.
January 29, 2011 at 9:49 am
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!