This article was originally included in the October issue of the Engine Yard Newsletter. To read more posts like this one, subscribe to the [_Engine Yard Newsletter](http://www.engineyard.com/newsletter)._
In __Inside Rails, Yehuda Katz, Rails expert and core team member, and Carl Lerche, Rails expert and full-time contributor, present expert advice and insight on the Rails platform and Rails development.
In previous versions of Rails, adding a new rendering option to Rails required performing an
alias_method_chainon the render method, adding your new options, and hoping they didn't conflict with any of the other code in the rendering pipeline.
Rails 3 makes rendering options a first class citizen, and uses the same new system internally that plugins authors are expected to use. Before we get into how you can use this feature yourself, let's take a look at how Rails uses it:
Here, we are creating a new
render :json option, which behaves exactly like
render :json in Rails 2.3. In the
render_json method, we use the same lower-level (but still public) APIs that are used by Rails itself to set the MIME type and response body. Using a render option entirely skips the rest of the render pipeline, so you don't have to worry about blocking normal template selection and rendering, or any other internal changes that might break your added option.
Next, let's take a look at adding a new render :pdf option. We'll use JRuby and the Flying Saucer library, which takes HTML and CSS and converts it to a PDF file. The syntax for the new option will be
render :pdf => "template_name", :css => %w(main.css print.pdf), :layout => "print".
In order to understand how to do this, let's first take a look at the code necessary to use Flying Saucer in JRuby. First, you'll need to grab the Flying Saucer jars (you can get them from my Muse git repo). Next, let's write the code necessary to convert HTML and CSS to PDF with Flying Saucer:
It's a bit verbose, but it does work. Now that we have a way to make the PDF, let's wire it up into a render option.
You'd also need to register the PDF mime type:
You could now do the following in a controller:
The tricky bits of this process are now reserved to figuring out how to build and return the output, not how to inject your option into render. Pretty cool, no?