I want to use a Rake task to cache my sitemap so that requests for sitemap.xml
won't take forever. Here's what I have so far:
@posts = Post.all
sitemap = render_to_string :template => 'sitemap/sitemap', :locals => {:posts => @posts}, :layout => false
Rails.cache.write('sitemap', sitemap)
But when I try to run this, I get an error:
undefined local variable or method `headers' for #<Object:0x100177298>
How can I render a template to a string from within Rake?
Here's how I did it:
Note that I converted my template to a partial to make this work
There is a post about how to be able to access ActionView::Base methods and context from rake task.
However, this is a monkeypatch. Why not use the rails' cache mechanism to accomplish caching? :)
Later edit: The render_to_string function is defined in ActionController::Base context.
Below is a solution on how to make it work from rake tasks, taken from omninerd.
Recently I wanted to take a rake task defined like Horace Loeb mentioned and translate it into a self contained background job, but it didn't easily translate.
Here is my implementation for Rails 2.3.x because the Rails 3 implementation I found wouldn't work.
This is available as a gist: https://gist.github.com/1386052.
Then you can use the class above to create an OfflineTemplate to render your views in a rake task: