sidekiq worker 中的 render_to_string

PaR*_*Nos 3 pdfkit ruby-on-rails-3 sidekiq

我正在尝试在我的应用程序中生成一些 PDF,它会处理一些数据,然后创建结果的 PDF。我正在使用 PDFKit,因此需要简单地创建一个 HTML 视图,如果我在控制器中,这很好,但我想使用 Sidekiq 将处理推入后台线程。

我本来打算使用,render_to_string但由于它只是控制器的一部分,我不能在 Sidekiq 中使用它。

有什么办法可以做到这一点吗?我想尝试并坚持使用 Sidekiq,但如果不是,那么我想我只需要在控制器中完成所有操作?

PaR*_*Nos 5

好的,我采用了不同的方法。

我已经创建了一个直接从工作类调用的抽象控制器,如下所述http://www.whatastruggle.com/generating-pdfs-in-background

不管怎么说,还是要谢谢你

编辑

似乎链接已死,因此总结一下有效的方法:

创建一个新的控制器,这将是渲染控制器

渲染控制器.rb

class RenderingController < AbstractController::Base
  include AbstractController::Rendering
  include ActionView::Layouts
  include AbstractController::Helpers
  include AbstractController::Translation
  include AbstractController::AssetPaths
  include Rails.application.routes.url_helpers
  include WickedPdf::PdfHelper

  self.view_paths = 'app/views'
end
Run Code Online (Sandbox Code Playgroud)

然后在任何需要使用它的地方

rc = RenderingController.new
rc.render_to_string(template: 'template/name', locals: { local: value })
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用 Rails 5+,则不再需要这样做,因为它们启用了控制器之外的渲染。相反,您现在可以这样做:

ApplicationController.render :index
Run Code Online (Sandbox Code Playgroud)

在此处获得更多详细信息