Prawn - NoMethodError: private method `p' called for object

Prawn - NoMethodError: private method `p' called for object

我正在尝试生成 pdf,但出于某种原因,当我尝试呈现 pdf 时,总是出现无方法错误。完全不知道该怎么做,因为我现在正在尝试的是渲染一个空白的 pdf。

NoMethodError: private method `p' called for #<OrderPdfCreator:0x007f9365053a20>

OrderController

require 'order_pdf_creator'

  def print_store_invoice
    # print the store invoice...
    @order = Order.find_by_id(params[:id])
    # create the pdf
    pdf = OrderPdfCreator.new(@order)

    render :attachment => pdf.p, :filename => "#{@order.id}.pdf", :layout => false
  end

OrderPdfCreator.rb

# encoding: UTF-8
require 'open-uri'

class OrderPdfCreator < BasePdfCreator

  def initialize(order)

    @pdf = Prawn::Document.new(:page_size => 'A4')
    @pdf.font_size = 14
    @order_pdf = order

    file_path = File.join(Rails.root,'tmp',"#{@order_pdf.id}.pdf")
    p = File.open(file_path, 'wb') { |f| f.puts @pdf.render }

  end

end

BasePdfCreator.rb

# encoding: UTF-8
class BasePdfCreator

  private

  def blank_line
    @pdf.text ' '
  end
end

错误说明了一切。你正在调用一个你不应该调用的方法。具体在这一行:

render :attachment => pdf.p, :filename => "#{@order.id}.pdf", :layout => false

改为:

render :attachment => pdf, :filename => "#{@order.id}.pdf", :layout => false

然后在您的初始化方法中,更改:

p = File.open(file_path, 'wb') { |f| f.puts @pdf.render }

至:

@pdf

Rails(好吧,ruby)总是 returns 方法中最后一条语句的结果(至少在默认情况下如此)。

编辑

好的,我明白发生了什么。我个人会将 initialize 方法重命名为其他名称(例如 createPDF),因此它 returns 是虾文档对象而不是 OrderPdfCreator 对象。所以在你的控制器中你会有:

pdf = OrderPdfCreator.new
pdf.createPDF
send_data pdf.render, :type => 'application/pdf', disposition: 'inline'