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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With