Hello and happy Friday!
Another week is swiftly drawing to a close and I’ve been intrigued recently with improving my Rails workflow with generators. It appeals to me that I can plant various configs, initializers, and templates into a generator and have a command line interaction similar to how we create a new rails app.
I’ve only read the first couple of chapters of the Rails Guides on this topic and wanted to share in sort of a clef-note style.
Step 0: Gather the Details of A Current Generator
This is where the Rails documentation starts, basically we can look at a list of commands and options to run on our command line for a specific generator. If you’re not familiar with what a generator is, Rails has a generator called
rails that we use to generate a default file tree that becomes our new application if we pass it a parameter of
Here’s are a few illustrations as an example:
From within our new or-in this case-existing Rails project folder we can just type
rails generate into our command line and this will provide us with a list of generators available currently in our application.
In order to see a list of commands and options for a specific generator, we can scroll down and see a list of gems that include generators and pick one to take a look at.
Lets see what a devise generator’s commands and options are:
Now that we have selected a generator to inspect, we can run a command that has the form of
rails g [generator_name] --help. So the Devise views generator would be
rails g devise:views --help and would return something like:
Now we that we can look into a generator’s commands and options from the command line, lets build our first generator!
Step 1: Our first Generator!
The first thing we need to do as create a home for our new generator files in our application file tree.
Here’s an example pulled straight from the source (the Rails documentation):
Here we see our initializer generator’s only method named
create_initializer_file. This method delegates to
create_file which is inherited from the
Lets run our generator by typing
rails g initializer in our command prompt. Now our generator creates the initializer file for us!
I didn’t cover an awful lot today, but the next time I post on this topic we’ll pick up where I left off in the documentation, Step 2: creating generators with generators 🙂
PS. Here are two videos from Ryan Bates:
I’ll be watching these episodes over the weekend to increase my understanding of generators, his screencasts are always very informative.
Have a great weekend 🙂
Categories: Ruby on rails