This guide is about generators in Rails 3, previous versions are not covered.
1 First Contact
When you create an application using the rails command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking rails generate:
$ rails new myapp
$ cd myapp
$ rails generate
You will get a list of all generators that comes with Rails. If you need a detailed description of the helper generator, for example, you can simply do:
$ rails generate helper --help
2 Creating Your First Generator
Since Rails 3.0, generators are built on top of Thor. Thor provides powerful options parsing and a great API for manipulating files. For instance, let’s build a generator that creates an initializer file named initializer.rb inside config/initializers.
The first step is to create a file at lib/generators/initializer_generator.rb with the following content:
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
Our new generator is quite simple: it inherits from Rails::Generators::Base and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the create_file method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you’ll feel right at home with the new generators API.
To invoke our new generator, we just need to do:
$ rails generate initializer
Before we go on, let’s see our brand new generator description:
$ rails generate initializer --help
Rails is usually able to generate good descriptions if a generator is namespaced, as ActiveRecord::Generators::ModelGenerator, but not in this particular case. We can solve this problem in two ways. The first one is calling desc inside our generator:
class InitializerGenerator < Rails::Generators::Base
desc "This generator creates an initializer file at config/initializers"
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
Now we can see the new description by invoking --help on the new generator. The second way to add a description is by creating a file named USAGE in the same directory as our generator. We are going to do that in the next step.
3 Creating Generators with Generators
Generators themselves have a generator:
$ rails generate generator initializer
create lib/generators/initializer
create lib/generators/initializer/initializer_generator.rb
create lib/generators/initializer/USAGE
create lib/generators/initializer/templates
This is the generator just created:
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
end
First, notice that we are inheriting from Rails::Generators::NamedBase instead of Rails::Generators::Base. This means that our generator expects at least one argument, which will be the name of the initializer.
We can see that by invoking the description of this new generator (don’t forget to delete the old generator file):
$ rails generate initializer --help
Usage:
rails generate initializer NAME [options]
We can also see that our new generator has a class method called source_root. This method points to where our generator templates will be placed, if any, and by default it points to the created directory lib/generators/initializer/templates.
In order to understand what a generator template means, let’s create the file lib/generators/initializer/templates/initializer.rb with the following content:
# Add initialization content here
And now let’s change the generator to copy this template when invoked:
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
def copy_initializer_file
copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
end
end
And let’s execute our generator:
$ rails generate initializer core_extensions
We can see that now a initializer named core_extensions was created at config/initializers/core_extensions.rb with the contents of our template. That means that copy_file copied a file in our source root to the destination path we gave. The method file_name is automatically created when we inherit from Rails::Generators::NamedBase.
4 Generators Lookup
When you run rails generate initializer core_extensions Rails requires these files in turn until one is found:
rails/generators/initializer/initializer_generator.rb
generators/initializer/initializer_generator.rb
rails/generators/initializer_generator.rb
generators/initializer_generator.rb
If none is found you get an error message.
The examples above put files under the application’s lib because said directoty belongs to $LOAD_PATH.
5 Customizing Your Workflow
Rails own generators are flexible enough to let you customize scaffolding. They can be configured in config/application.rb, these are some defaults:
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => true
end
Before we customize our workflow, let’s first see what our scaffold looks like:
$ rails generate scaffold User name:string
invoke active_record
create db/migrate/20091120125558_create_users.rb
create app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
route resources :users
invoke scaffold_controller
create app/controllers/users_controller.rb
invoke erb
create app/views/users
create app/views/users/index.html.erb
create app/views/users/edit.html.erb
create app/views/users/show.html.erb
create app/views/users/new.html.erb
create app/views/users/_form.html.erb
invoke test_unit
create test/functional/users_controller_test.rb
invoke helper
create app/helpers/users_helper.rb
invoke test_unit
create test/unit/helpers/users_helper_test.rb
invoke stylesheets
create public/stylesheets/scaffold.css
Looking at this output, it’s easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn’t actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.
Our first customization on the workflow will be to stop generating stylesheets and test fixtures for scaffolds. We can achieve that by changing our configuration to the following:
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
end
If we generate another resource with the scaffold generator, we can notice that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it’s just a matter of adding their gems to your application and configuring your generators.
To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator:
$ rails generate generator my_helper
After that, we can delete both the templates directory and the source_root class method from our new generators, because we are not going to need them. So our new generator looks like the following:
class MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
attr_reader :#{plural_name}, :#{plural_name.singularize}
end
FILE
end
end
We can try out our new generator by creating a helper for users:
$ rails generate my_helper products
And it will generate the following helper file in app/helpers:
module ProductsHelper
attr_reader :products, :product
end
Which is what we expected. We can now tell scaffold to use our new helper generator by editing config/application.rb once again:
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
g.helper :my_helper
end
and see it in action when invoking the generator:
$ rails generate scaffold Post body:text
[...]
invoke my_helper
create app/helpers/posts_helper.rb
We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.
Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible.
To do that, we can change the generator this way:
class MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
attr_reader :#{plural_name}, :#{plural_name.singularize}
end
FILE
end
hook_for :test_framework
end
Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both MyHelper::Generators::TestUnitGenerator and TestUnit::Generators::MyHelperGenerator. Since none of those are defined, we can tell our generator to invoke TestUnit::Generators::HelperGenerator instead, which is defined since it’s a Rails generator. To do that, we just need to add:
# Search for :helper instead of :my_helper
hook_for :test_framework, :as => :helper
And now you can re-run scaffold for another resource and see it generating tests as well!
6 Customizing Your Workflow by Changing Generators Templates
In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it’s by replacing the templates of already existing generators, in that case Rails::Generators::HelperGenerator.
In Rails 3.0 and above, generators don’t just look in the source root for templates, they also search for templates in other paths. And one of them is lib/templates. Since we want to customize Rails::Generators::HelperGenerator, we can do that by simply making a template copy inside lib/templates/rails/helper with the name helper.rb. So let’s create that file with the following content:
module <%= class_name %>Helper
attr_reader :<%= plural_name %>, <%= plural_name.singularize %>
end
and revert the last change in config/application.rb:
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
end
If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating edit.html.erb, index.html.erb and so on inside lib/templates/erb/scaffold.
7 Adding Generators Fallbacks
One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a TestUnit generator if none was found under the Shoulda namespace.
We can easily simulate this behavior by changing our config/application.rb once again:
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :shoulda, :fixture => false
g.stylesheets false
# Add a fallback!
g.fallbacks[:shoulda] = :test_unit
end
Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators:
$ rails generate scaffold Comment body:text
invoke active_record
create db/migrate/20091120151323_create_comments.rb
create app/models/comment.rb
invoke shoulda
create test/unit/comment_test.rb
create test/fixtures/comments.yml
route map.resources :comments
invoke scaffold_controller
create app/controllers/comments_controller.rb
invoke erb
create app/views/comments
create app/views/comments/index.html.erb
create app/views/comments/edit.html.erb
create app/views/comments/show.html.erb
create app/views/comments/new.html.erb
create app/views/comments/_form.html.erb
create app/views/layouts/comments.html.erb
invoke shoulda
create test/functional/comments_controller_test.rb
invoke my_helper
create app/helpers/comments_helper.rb
invoke shoulda
create test/unit/helpers/comments_helper_test.rb
Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.
8 Changelog
- August 23, 2010: Edit pass by Xavier Noria
- April 30, 2010: Reviewed by José Valim
- November 20, 2009: First version by José Valim