无法在泛型类中呈现视图

时间:2010-06-18 00:52:44

标签: ruby-on-rails rendering

我正在尝试封装用于在单独的类中生成我的站点地图的逻辑,因此我可以使用Delayed :: Job来生成带外:

class ViewCacher
  include ActionController::UrlWriter

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

  def cache_sitemap
    songs = Song.all

    sitemap = @av.render 'sitemap/sitemap', :songs => songs
    Rails.cache.write('sitemap', sitemap)
  end
end

但每当我尝试ViewCacher.new.cache_sitemap时,我都会收到此错误:

ActionView::TemplateError: 
ActionView::TemplateError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.url_for) on line #5 of app/views/sitemap/_sitemap.builder:

我认为这意味着ActionController::UrlWriter未包含在正确的位置,但我真的不知道

1 个答案:

答案 0 :(得分:0)

这是否符合您的要求?这是未经考验的,只是一个想法。

lib / view_cacher.rb

中的

module ViewCacher
  def self.included(base)
    base.class_eval do
      #you probably don't even need to include this
      include ActionController::UrlWriter
      attr_accessor :sitemap

      def initialize
        @av = ActionView::Base.new(Rails::Configuration.new.view_path)
        @av.class_eval do
          include ApplicationHelper      
        end
        cache_sitemap
        super
      end

      def cache_sitemap
        songs = Song.all

        sitemap = @av.render 'sitemap/sitemap', :songs => songs
        Rails.cache.write('sitemap', sitemap)
      end
    end
  end
end

然后你想要渲染的任何地方(我想你的SitemapController中可能):

app / controllers / sitemap_controller.rb

class SitemapController < ApplicationController
  include ViewCacher

  # action to render the cached view
  def index
    #sitemap is a string containing the rendered text from the partial located on
    #the disk at Rails::Configuration.new.view_path

    # you really wouldn't want to do this, I'm just demonstrating that the cached
    # render and the uncached render will be the same format, but the data could be
    # different depending on when the last update to the the Songs table happened
    if params[:cached]
      @songs = Song.all

      # cached render
      render :text => sitemap
    else
      # uncached render
      render 'sitemap/sitemap', :songs => @songs
    end
  end
end