Rails / Prawn: how can I use rail helpers inside the Prawn class?

I am trying to use rails 3.2 helpers inside the prawn class, but rails throws:

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

Shrimp class

 class QuotePdf < Prawn::Document def initialize(quote) super() text "sum: #{number_with_precision(quote.sum)}" end end 

controller

 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 

Thank you for your help.

+7
source share
3 answers

You must explicitly include ActionView::Helpers::NumberHelper (or any other helper class / module) in your drawing document class.

 class QuotePdf < Prawn::Document include ActionView::Helpers::NumberHelper # <- def initialize(quote) super() text "sum: #{number_with_precision(quote.sum)}" end end 
+11
source

Just pass view_context to the initializer of the subclass of Prine.

 def initialize(quote, view_context) super() @view = view_context end 

in the controller, change to:

 QuotePdf.new(@quote, view_context) 

then in a subclass of Prawn this will work:

 @view.number_with_precision(quote.sum) 
+6
source

If the iafonov solution does not work, you can simply enable NumberHelper without a prefix.

+5
source

All Articles