2012-03-14 68 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

相关问题