Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDF generating with prawn - How can I acces variable in Prawn.generate?

I'm trying to generate pdf using Prawn

@buyer = Buyer.last
Prawn::Document.generate("samle.pdf") do
  text "hello #{@buyer.name} world"
end

but this obviously doesn't work (only if I use class variable @@buyer), my question is what is the proper way of passing variable to Prawn::Document.generate

(I know the solution to this is prawnto but I'm experimenting little bit ...and also it's a sinatra project)

like image 771
equivalent8 Avatar asked Apr 16 '11 09:04

equivalent8


1 Answers

From http://rdoc.info/github/sandal/prawn/master/Prawn/Document#generate-class_method it looks like if you pass a variable in to your block it will be then evaluated in the current context. So try:

@buyer = Buyer.last
Prawn::Document.generate("samle.pdf") do |pdf|
  pdf.text "hello #{@buyer.name} world"
end

Edit: To be more clear, this means that rather than the block being evaluated inside a new Prawn::Document object, the Prawn::Document object is instead passed into the block. The block is then evaluated within the current object so your instance variables are still in scope.

like image 175
Tapio Saarinen Avatar answered Oct 31 '22 13:10

Tapio Saarinen