Time has come for me to write a Rails generator, and as you’re guessing right now, my first step was taking a look at the Guides. They give you a pretty good idea on what you can do (despite of being for Rails 3.0), but as my friend Santiago always say, there’s no better documentation than the source code itself. So, my second step was to dive into the code. You should definitely read the code, great stuff there.
After some time reading, I decided it was time for me to start playing around with that, so here it comes:
First thing you should know, is that all Rails generators are derived from a class called “Rails::Generator::Base.” But, if we derive our generator class from NamedBase instead of Base, then we’ll get the ability to take a name parameter from the script/generate command line. With that in mind, you can start writing the generator skeleton:
1 2 3 4 5 6 7
In order to make the generator work on your Rails 2.3 application, you should place this file under ‘lib/generators/widget/widget_generator.rb’
Is on the manifest method where the magic occurs. Depending on what exactly we want our generator to do, is what we’re going to code inside it. In my case, I wanted to behave very similar to the scaffold, so I wanted a controller class, a model, views, migration, etc… You can look at the templates of the scaffold generator, they will give you a very clear idea on how to use them. Then, you should place your templates under ‘lib/generators/widget/templates/’
In most cases, you will want your generator to receive several arguments. Best way is to have an initialize method to take care of that, just like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Until now, we’re just initializing the generator, but it’s not doing anything yet. Let’s add some action on our manifest method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Cool, now we are generating a controller from our template, a model, a migration, among others…Nice!
You can also add a protected banner method, to display the usage of the generator right on the console:
1 2 3 4
And that’s all !! You can now generate all the widgets you want. The command to run this would be:
Have fun generating!!