【问题标题】:Trouble rendering a view inside a generic class在泛型类中渲染视图时遇到问题
【发布时间】:2010-06-18 00:52:44
【问题描述】:

我正在尝试将生成站点地图的逻辑封装在一个单独的类中,以便我可以使用 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 没有包含在正确的位置,但我真的不知道

【问题讨论】:

    标签: ruby-on-rails rendering


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多