简体   繁体   中英

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

I'm trying to generate a pdf and for some reason i keep getting a no method error when i try to render the pdf. Literally no idea what to do as all i'm trying at this point is to render a blank 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

The error says it all. You are calling a method you shouldn't. Specifically in this line:

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

Change it to:

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

And in your initialize method, change:

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

to:

@pdf

Rails (well, ruby) always returns the result of the last statement in a method (at least by default).

EDIT

Ok, so I see what's happening. I personally would rename the initialize method to something else (say createPDF ) so it returns the prawn document object and not a OrderPdfCreator object. So in your controller you would have:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM