Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Prawn: how do I use rails helpers inside a Prawn class?

I'm trying to use rails 3.2 helpers inside a prawn class, but rails throws:

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

Prawn 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

Thanks for your help.

like image 712
Laura Avatar asked Mar 14 '12 19:03

Laura


People also ask

How to use prawn with rails 5?

In a few lines below, I would like to explain how to use it with Rails 5. This will be just a minimal example with Hello World! document as a result. 1. Install Prawn gem: Please check out what is the current gem version on RubyGems.org or Github and add similar line to your Gemfile: 2. Extend one of your actions

Do I need to mention prawn-rails in my projects Gemfile?

Note: prawn and prawn-table are dependencies of prawn-rails so there is no need to mention it in the projects Gemfile unless you want to use a specific version of either of those libraries.

What is prawn_document in prawnrails?

It provides a helper called prawn_document which builds a PrawnRails::Document with default options. You can override any options as you please. Example: No need to call pdf.render, it is called by prawn_document.

Can prawn-rails override the header of a file?

If you've already set this, prawn-rails will not override it. Here's an example of setting the header directly: You can also override the file's name from the controller via @filename: If no options are given, the file's name will match to your browser's default and the delivery format will default to inline.


2 Answers

Just pass the view_context to the Prawn sub-class initializer.

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

in Controller, change to:

QuotePdf.new(@quote, view_context)

then in Prawn sub-class, this will work:

@view.number_with_precision(quote.sum)
like image 113
John Nguyen Avatar answered Nov 11 '22 07:11

John Nguyen


If iafonov solution doesn't work, you may just have to include NumberHelper without the prefix.

like image 23
siekfried Avatar answered Nov 11 '22 05:11

siekfried