来自rake任务的render_to_string

时间:2010-04-12 04:04:45

标签: ruby-on-rails rake

我想使用Rake任务来缓存我的站点地图,以便sitemap.xml的请求不会永远存在。这是我到目前为止所做的:

  @posts = Post.all

  sitemap = render_to_string :template => 'sitemap/sitemap', :locals => {:posts => @posts}, :layout => false
  Rails.cache.write('sitemap', sitemap)

但是当我尝试运行时,我收到一个错误:

undefined local variable or method `headers' for #<Object:0x100177298>

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

3 个答案:

答案 0 :(得分:9)

我是这样做的:

  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)

请注意,我将模板转换为部分模板以使其正常工作

答案 1 :(得分:4)

有一个post关于如何从rake任务访问ActionView :: Base方法和上下文。

然而,这是一个monkeypatch。为什么不使用rails'cache mechanism来完成缓存? :)

稍后编辑: render_to_string 函数在ActionController :: Base上下文中定义。

以下是有关如何通过omninerd取得的rake任务使其工作的解决方案。

# 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}
  )
)

答案 2 :(得分:1)

最近我想采取像Horace Loeb所提到的rake任务并将其翻译成一个自包含的后台工作,但它并不容易翻译。

这是我对Rails 2.3.x的实现,因为我找到的Rails 3 implementation不起作用。

# Public: Template to render views outside the context of a controller.
#
# Useful for rendering views in rake tasks or background jobs when a
# controller is unavailable.
#
# Examples
#
#   template = OfflineTemplate.new(:users)
#   template.render("users/index", :layout => false, :locals => { :users => users })
#
#   template = OfflineTemplate.new(ProjectsHelper, PermissionsHelper)
#   template.render("projects/recent", :projects => recent_projects)
#
class OfflineTemplate
  include ActionController::UrlWriter
  include ActionController::Helpers::ClassMethods

  # Public: Returns the ActionView::Base internal view.
  attr_reader :view

  # Public: Convenience method  to
  delegate :render, :to => :view

  # Public: Initialize an offline template for the current Rails environment.
  #
  # helpers - The Rails helpers to include (listed as symbols or modules).
  def initialize(*helpers)
    helper(helpers + [ApplicationHelper])
    @view = ActionView::Base.new(Rails.configuration.view_path, {}, self)
    @view.class.send(:include, master_helper_module)
  end

  private

  # Internal: Required to use ActionConroller::Helpers.
  #
  # Returns a Module to collect helper methods.
  def master_helper_module
    @master_helper_module ||= Module.new
  end
end

这可以作为要点:https://gist.github.com/1386052

然后,您可以使用上面的类创建一个OfflineTemplate来在rake任务中呈现您的视图:

task :recent_projects => :environment do 
  template = OfflineTemplate.new(ProjectsHelper, PermissionsHelper)
  puts template.render("projects/recent", :projects => recent_projects)
end