May 11 prawn + prawnto: easy ruby PDF generation, but a Rails 2.1 gotcha

tags: pdf prawn prawnto rails 2.1.0 gotcha | comments

Prawn is the new crack to generate pdfs in ruby. Its Rails add-on prawnto make Rails reports and documents generation a charm. But still there’s a little gotcha that can stop you from using it in your Rails 2.1.0 app out of the box.

I’ve used rtex for a while to generate my pdfs, but prawn+prawnto really beated it. Take a look at how simple it is to create pdfs.

First installation, the gem and the plugin:

  sudo gem install prawn
  script/plugin install git://github.com/thorny-sun/prawnto.git

and your are good to go, in your views:

#  template some.pdf.prawn
pdf.text "Hello pdf world", :size => 30, :style => :bold
pdf.move_down(30)

# and lot's more
pdf.start_new_page
pdf.text "another page, and so on..."

There are lots of resources around to get you started: railscasts, prawnto have also lots of examples to get you going. Good work kids!

Rails 2.1 gotcha

When trying to start your Rails 2.1 server you get an error:

$ script/server
...
uninitialized constant ActiveSupport::Memoizable (NameError) 

the thing is prawnto relies on Rails memoization feature that’s not available before Rails 2.2. There’s a ticket on lighthouse for the issue.

I got my hands dirty and patched prawnto for Rails older than 2.2 by disconnecting memoization usage:

# lib/prawnto/template_handler/compile_support.rb

# wrapping memoization usage with version checking
unless Gem::Version.new(Rails.version) < Gem::Version.new("2.2.0")
    extend ActiveSupport::Memoizable
end

# and the same everywhere it is needed
unless Gem::Version.new(Rails.version) < Gem::Version.new("2.2.0")
    memoize :ie_request?
end

The trick is using rubygems Version class and comparing versions is a candy. Grab it on my fork if you want

blog comments powered by Disqus