render_to_string in Rails Models or Rake Tasks

Citation: Mark A. McBride, render_to_string in Rails Models or Rake Tasks, OmniNerd.com, 25 December 2008, accessed on 16 March 2010 from http://www.omninerd.com/articles/render_to_string_in_Rails_Models_or_Rake_Tasks
Tags: render, rails, mvc, and ruby

I recently ran into an issue with Rails that was preventing me from caching view content in my background rake tasks for a Rails app. There is a function available in the controller space called render_to_string that returns the rendered view template that I want to cache, but the problem is that I want to do my caching while not in the controller. The solution is easy, but not obvious.

# In a rake task:
av = ActionView::Base.new(Rails::Configuration.new.view_path)
Rails.cache.write(
  "cache_var", 
  av.render(
    :partial => "view_folder/some_partial", 
    :locals => {:a_var => @some_var}
  )
)

The magic is in the av variable that gives access to rendering your views. Once rendered, you can cache your view code like anything else.

Credit to Cory Patterson who led me in the right direction after hours of searching.