Creating your own generators


#1

So I’m interested in creating an application specific generator. The
script/generate command tells me that all I have to do is put a
generator in my rails_root/generators:

  1. Unzip to directory /Users/{username}/.rails/generators/login
    to use the generator with all your Rails apps
    or to {app_root}/generators/login
    to use with this app only.

So I created a generators directory and plop in my generator. Upon
executing script/generate {generator_name} I get:

Couldn’t find ‘{generator_name}’ generator

What do I need to do differently? Is there any documentation on creating
generators? I found:

http://wiki.rubyonrails.com/rails/pages/Generators

But it didn’t talk about creating your own generator. A script/generate generator command would be most helpful for bootstrapping the creation
process of new generators.


John L.
http://wiseheartdesign.com


#2

I have created my own generator in the context of a plugin, and it
worked
pretty well. There isn’t a functional difference between the two, so
maybe
you would be willing to go that route.

As I understand it, if you want to create a generator, you follow these
steps. Imagine the generator is going to be called “widget_generator”

  1. Create the directory vendor/plugins/widget/generators/widget
  2. Create the file
    vendor/plugins/widget/generators/widget/widget_generator.rb
  3. In that file, put this code:

class WidgetGenerator < Rails::Generator::Base
def manifest
record do |m|
### generator commands …
end
end
end

Note all the file, directory and class names - they are very important.
If
everything worked right, when you type “ruby script/generate” you should
see
“widget_generator” listed. Note that you can also inherit from NamedBase
and
you will get some command line argument support - though I haven’t
explored
that so I can’t speak to it.

Sadly, generators are pretty badly documented. I suggest browsing the
Rails
source to see what you can do with them. In your gems installation, the
relevant files are in rails/lib/rails_generator.

If you want to look at a working generator, the plugin I mentioned above
can
be downloaded from http://rubyforge.org/projects/realapps-cms/ . Just
click
“Files” and get the latest zip. Unzip it into vendor/plugins and then
you
can run it with ‘ruby script/generate realapps_cms’.

Hope that helps and good luck!

Justin


#3

I also highly recommend Chad F.'s book, “Rails Recipes.” Chad has
a recipe in the book on creating your own generators. Plus you get
like 70+ more really cool things all for one low price. :slight_smile:

Michael


#4

Justin B. wrote:

I have created my own generator in the context of a plugin, and it worked
pretty well. There isn’t a functional difference between the two, so maybe
you would be willing to go that route.

I did try this, and it worked, but it turns out the directory is
‘lib/generators’ not ‘generators’ like the usage guidelines describe.


John L.
http://johnwlong.com