Проблема с отображением представления внутри общего класса - PullRequest
0 голосов
/ 18 июня 2010

Я пытаюсь инкапсулировать логику для создания моей карты сайта в отдельный класс, чтобы я мог использовать 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 голосов
/ 18 июня 2010

Это делает то, что вы пытаетесь сделать? Это не проверено, просто идея.

in 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):

in 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...