Рендеринг вида (с частичными представлениями) из задачи rake

Я получил следующий код в задаче rake:

class PdfExporter < ActionView::Base
  include Rails.application.routes.url_helpers
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::UrlHelper

  def generate_pdf_from_html  
    content = File.read('path/to/view.html.erb')
    erb = ERB.new(content)
    html_content = erb.result(binding)

    # ... some pdf stuff
  end
end

Проблема - указанный view.html.erb отображает в нем другое представление.

  <%= render partial: 'path/to/another_view' %>

И erb.result(binding) выдает следующую ошибку:

Отсутствует частичный /path/to/another_view

Если частичные фрагменты отсутствуют, представление отображается нормально.

Я уверен, что путь правильный, но кажется, что я не могу отобразить его из задачи rake.

Почему? Могу ли я включить какой-нибудь полезный помощник?

Я не хочу создавать экземпляры контроллеров.

РЕДАКТИРОВАТЬ:

Searched in:

пусто. Вероятно, это означает, что ActionView не «знает», где искать представление.


person fiction    schedule 09.06.2014    source источник
comment
Вы пробовали использовать абсолютный путь, например <%= render partial: "#{Rails.root}/app/views/foo/bar" %>?   -  person Baldrick    schedule 09.06.2014


Ответы (1)


Вот пример моей задачи rake, которая создает html-файл из представления. Чтобы это сработало, вы должны успокоить ActionView, переопределив некоторые значения по умолчанию и передав поддельный контроллер и запрос:

  desc 'Example of writing a view to a file'
  task :example => :environment do

    # View that works with Rake
    class RakeActionView < ActionView::Base
      include Rails.application.routes.url_helpers
      include ::ApplicationHelper
      # Include other helpers that you will use

      # Make sure this matches the expected environment, e.g. localhost for dev
      # and full domain for prod
      def default_url_options
        {host: 'localhost:3000'}
      end

      # It is safe to assume that the rake request is legit
      def protect_against_forgery?
        false
      end
    end

    # build a simple controller to process the view
    controller = ActionController::Base.new
    controller.class_eval do
      include Rails.application.routes.url_helpers
      include ::ApplicationHelper
    end

    # build a fake request
    controller.request = ActionDispatch::TestRequest.new

    # build the rake view with the path to the app views
    view = RakeActionView.new(Rails.root.join('app', 'views'), {}, controller)

    # example assigning instance @variables to the view
    view.assign( :user => User.first )

    # Render the view to html
    html = view.render(template: 'relative/path/to/template', layout: 'layouts/example')

    # Write html to temp file and then copy to destination
    temp = Tempfile.new('example_file')
    temp.write(html)
    FileUtils.cp( temp.path, 'path/to/exmple_file' )

    # optionally set permissions on file
    File.chmod(0774, 'path/to/exmple_file')

    # close up the temp file
    temp.close
    temp.unlink
  end

Похоже, проблема, с которой вы столкнулись, устранена с помощью RakeActionView.new(Rails.root.join('app', 'views'), {}, controller), который устанавливает путь, по которому ActionView ищет шаблоны.

person mguymon    schedule 09.06.2014