Creating a Rails generator

Written by Keith McDonnell. Last updated on Saturday, September 22, 2007.

In this article, I’ll show you how a custom generator can speed up your Rails workflow by copying some boilerplate code. For example, instead of copying and pasting CSS and HTML layout you can create a generator to do this for you.

If you’ve coded even the most basic Rail app you’ll be familiar with generators. We let ./script/generate & friends automate mundane & error prone tasks and leave us to get on with the fun stuff. If you’re not familiar with generators just read the Rails command line guide and expiriment with ./script/generate from the root of a Rails app directory.

Create a new app with a RailCasts style UI

Here’s a quick way to create a new rails app with Railscasts style presentation. The idea being that when you want to watch a new episode you can:

  1. create a new rails app rails_metal
  2. generate a RailsCasts style UI cd rails_metal && ./script/generate railscasts_ui
  3. start the server ./script/server and follow along

Seeing as you’ll probably use this on multiple, seperate Rails apps, the
generator should be saved in ~/.rails/generators/railscasts_ui .

  1. Create the generator directory
    mkdir -p /.rails/generators/railscasts_ui/templates
  1. Change to the generator directory
    cd /.rails/generators/railscasts_ui
  1. Create a documentation file
    touch USAGE
  1. Create the stylesheet
    touch templates/railscasts.css
  1. Create the layout file
    touch templates/application.rhtml
  1. Create the generator file edit templates/railscasts_ui.rb . Note that the class name must be a camel case version of the generator directory (RailscastsUi).

    class RailscastsUi < Rails::Generator::NamedBase
    def manifest
  2. record do |m|
  3. “#{RAILS_ROOT}/public/stylesheets”
  4. m.file “railscasts.css”, “#{RAILS_ROOT}/public/stylesheets/railscasts.css”
  5. “#{RAILS_ROOT}/app/views/layouts”
  6. m.file “application.rhtml”, “#{RAILS_ROOT}/app/views/layouts/application.rhtml”
  7. end

You can use this technique to automate any static file creation or copying, e.g. if you want to have different stylesheets for development and production.


If you'd like to discuss this article, you can send me an email and/or publish an article online and link back to this page.