Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render_to_string from a rake task

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?

like image 976
Tom Lehman Avatar asked Apr 12 '10 04:04

Tom Lehman


People also ask

What is a rake task?

Rake is a software task management and build automation tool created by Jim Weirich. It allows the user to specify tasks and describe dependencies as well as to group tasks in a namespace. It is similar in to SCons and Make.

What is environment rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.

Where are Rake tasks defined?

In any Rails application you can see which rake tasks are available - either by running rake -AT (or rake --all --tasks) to see all tasks, or rake -T (or rake --tasks ) to see all tasks with descriptions.


1 Answers

Here's how I did it:

  av = ActionView::Base.new(Rails::Configuration.new.view_path)
  av.class_eval do
    include ApplicationHelper
  end

  include ActionController::UrlWriter
  default_url_options[:host] = 'mysite.com'

  posts = Post.all

  sitemap = av.render 'sitemap/sitemap', :posts => posts
  Rails.cache.write('sitemap', sitemap)

Note that I converted my template to a partial to make this work

like image 128
Tom Lehman Avatar answered Sep 29 '22 06:09

Tom Lehman