This morning there was a guy in the rails IRC room asking about using helpers in his controller and I recently wrote an app that used the great pdf-writer gem to generate some pdfs and used helpers in the controller for formatting in the pdf. If you are going to generate very complicated pdfs, its best not to put your pdf formatting code directly in the controller, but if you need just a real quick pdf generated, this works great.

First, create a new class in your application controller:

class Helper
include Singleton
include ActionView::Helpers::PdfHelper #or whatever helpers you want
end

I wanted to use my pdf_helpers
..and then:

def pdf_helpers
Helper.instance
end

Will create an instance of your new class.

Now, go to your pdf controller (or whatever) and simply:

pdf.text pdf_helpers.my_crazy_helper(@foo.bar)

The pdf.text part is not the important part, thats just for pdf-writer, but what is is using “pdf_helpers.your_helper” to create a new instance of the helper class which will allow you to use that helper.


Leave a Comment


To insert code, wrap in <code></code> tags.




John Yerhot is Digg proof thanks to caching by WP Super Cache!