来自 rake 任务的 render_to_string [英] render_to_string from a rake task

查看:53
本文介绍了来自 rake 任务的 render_to_string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Rake 任务来缓存我的站点地图,以便对 sitemap.xml 的请求不会永远持续下去.这是我到目前为止所拥有的:

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>

如何在 Rake 中将模板渲染为字符串?

How can I render a template to a string from within Rake?

推荐答案

我是这样做的:

  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

这篇关于来自 rake 任务的 render_to_string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆