2012-03-14 62 views
7

我試圖用一個prawn類中rails 3.2幫手,但軌道拋出:Rails/Prawn:我如何在Prawn類中使用rails helper?

undefined method `number_with_precision' for #<QuotePdf:0x83d4188> 

蝦類

class QuotePdf < Prawn::Document 
    def initialize(quote) 
    super() 

    text "sum: #{number_with_precision(quote.sum)}" 
    end 
end 

控制器

def show 
    @quote = current_user.company.quotes.where(:id => params[:id]).first 
    head :unauthorized and return unless @quote 

    respond_with @quote, :layout => !params[:_pjax] do |format| 
    format.pdf do 
     send_data QuotePdf.new(@quote).render, filename: "Devis-#{@quote.date_emission.strftime("%d/%m/%Y")}.pdf", 
     type: "application/pdf" 
    end 
    end 
end 

感謝您的幫助。

回答

11

您必須在您的對蝦文檔類中明確包含ActionView::Helpers::NumberHelper(或任何其他幫助類/模塊)。

class QuotePdf < Prawn::Document 
    include ActionView::Helpers::NumberHelper # <- 

    def initialize(quote) 
    super() 

    text "sum: #{number_with_precision(quote.sum)}" 
    end 
end 
+0

Rails中3.2.11行之有效我。 Siekfried's沒有。謝謝! – 2013-05-07 04:10:29

+0

包括必須在最新的rails版本之外的類(定義類之前)! – mArtinko5MB 2013-12-03 10:00:47

5

如果iafonov解決方案不起作用,你可能只需要包括NumberHelper沒有前綴。

6

只需將view_context傳遞給Prawn子類初始值設定項即可。

def initialize(quote, view_context) 
    super() 
    @view = view_context 
end 
在控制器

,更改爲:

QuotePdf.new(@quote, view_context) 

然後在對蝦子類中,這將工作:

@view.number_with_precision(quote.sum) 
+0

我更喜歡這個方法,因爲它使@view和它的方法不同。這樣你就不會有ActionView中的某些東西在Prawn :: Document中意外地發現一些東西。 – sockmonk 2013-02-07 02:43:05

相關問題