我一直试图通过rails 5.1 app中的sidekiq和wicked_pdf生成PDF,但一直收到此错误:
2017-11-01T02:20:33.339Z 1780 TID-ovys2t32c GeneratePdfWorker JID-b3e9487113db23d65b179b1c INFO: start
2017-11-01T02:20:33.369Z 1780 TID-ovys2t32c GeneratePdfWorker JID-b3e9487113db23d65b179b1c INFO: fail: 0.03 sec
2017-11-01T02:20:33.371Z 1780 TID-ovys2t32c WARN: {"class":"GeneratePdfWorker","args":[2,1],"retry":false,"queue":"default","jid":"b3e9487113db23d65b179b1c","created_at":1509502833.334234,"enqueued_at":1509502833.3345}
2017-11-01T02:20:33.380Z 1780 TID-ovys2t32c WARN: NameError: undefined local variable or method `quote' for #<GeneratePdfWorker:0x007fb6d5cea070>
Did you mean? @quote
2017-11-01T02:20:33.380Z 1780 TID-ovys2t32c WARN: /Users/stefanbullivant/quottes/app/workers/generate_pdf_worker.rb:18:in `perform'
即使没有在av.render方法中传递本地,我也会收到此错误。关于导致它的原因的任何想法都表示赞赏。 quotes_controller.rb调用worker
def create_pdf
@quote = Quote.find(params[:id])
GeneratePdfWorker.perform_async(@quote.id, current_account.id)
redirect_to @quote
end
Generate_pdf_worker.rb
class GeneratePdfWorker
include Sidekiq::Worker
sidekiq_options retry: false
def perform(quote_id, account_id)
@quote = Quote.find(quote_id)
@account = Account.find(account_id)
# create an instance of ActionView, so we can use the render method outside of a controller
av = ActionView::Base.new()
av.view_paths = ActionController::Base.view_paths
# need these in case your view constructs any links or references any helper methods.
av.class_eval do
include Rails.application.routes.url_helpers
include ApplicationHelper
end
pdf = av.render pdf: "Quote ##{ @quote.id } for #{ @quote.customer_name }",
file: "#{ Rails.root }/tmp/pdfs/quote_#{@quote.id}_#{@quote.customer_name}.pdf",
template: 'quotes/create_pdf.html.erb',
layout: 'layouts/quotes_pdf.html.erb',
disposition: 'attachment',
disable_javascript: true,
enable_plugins: false,
locals: {
quote: @quote,
account: @account
}
# pdf_html = av.render :template => "quotes/create_pdf.html.erb",
# :layout => "layouts/quotes_pdf.html.erb",
# :locals => {
# quote: @quote,
# account: @account
# }
# use wicked_pdf gem to create PDF from the doc HTML
quote_pdf = WickedPdf.new.pdf_from_string(pdf, :page_size => 'A4')
# save PDF to disk
pdf_path = Rails.root.join('tmp', "quote.pdf")
File.open(pdf_path, 'wb') do |file|
file << quote_pdf
en
end
end
quotes_pdf.html.erb PDF布局
<!DOCTYPE html>
<html>
<head>
<title>Quottes</title>
<meta charset="utf-8" />
<meta name="ROBOTS" content="NOODP" />
<style>
<%= wicked_pdf_stylesheet_link_tag 'quote_pdf' -%>
</style>
</head>
<body>
<div class="container">
<%= yield %>
</div>
</body>
</html>
create_pdf.html.erb PDF视图(为了让事情先运行起来,每个本地只有两行)
<%= account.brand_name %>
<%= quote.customer_name %>
非常感谢任何关于让这种运行的建议。我已经玩了简单地在pdf视图中生成普通的html文本而没有传递任何变量但仍然得到这个错误,所以我很困惑是什么导致它。
答案 0 :(得分:0)
我有时也会忘记this - 似乎非常坚持第18行(我只能假设是渲染)正在查找本地的引用但无法找到它,当时定义了@quote。如果那是你的所有代码,那么我会假设没有接受更改。
我最好的建议(我希望有效)是你需要重启sidekiq!