Ben Scofield

Application templates in Rails 3

with 2 comments

Here’s a trick for creating modular templates in Rails 3: use the apply method

Say you like to use Rails templates, but you find them a little too inflexible – you want to use Cucumber, jQuery, and MongoDB, but not always together. You could create separate templates for each combination (and in fact, with Rails 2.3.x that’s what you have to do), but in Rails 3, things get a little easier. With 3, you can actually modularize your templates!

For instance, this gist removes the default Prototype JavaScript files from your app, and gives you a simple XHTML layout with Google’s hosted versions of jQuery all ready to go:

jQuery application template

This gist, on the other hand, requires the Cucumber and webrat gems and runs the Cucumber generator to set up the features directory, etc:

Cucumber application template

In current Rails, you’d either have to run these individually or put the code into a single file to get them to apply to a project; in Rails 3, however, you can create a separate template that applies both of them:

Aggregate template

In Rails 3, the directive to apply a template has been refactored into the apply command, which you can access inside a template, because they’re instance_eval‘d by the application generator. This opens up a whole new world of possibilities for remixing components, and should make starting new Rails applications even easier. One more reason to anticipate the arrival of 3!

Written by Ben

September 18th, 2009 at 7:00 am

Tagged with

2 Responses to 'Application templates in Rails 3'

Subscribe to comments with RSS or TrackBack to 'Application templates in Rails 3'.

  1. [...] On another post, Ben Scofield talks about apply method, which is also in Thor::Actions, and how to use it to dry your application templates. [...]

  2. Correct me if I’m wrong, but isn’t “load_template” from Rails 2.x templates equivalent to “apply”?

    Bradley Grzesiak

    23 Jan 10 at 9:03 pm

Leave a Reply