When learning Rails we all learn about generators. I still remember when I saw it for the first time. I just fell in love with it. Writing a single command can create useful files and directories for me. Until recently I never had a chance to create a generator. Yesterday I did a blog on using Vue.js with Rails and I saw that I had to create a few files every time I wanted to add Vue to a view. So I went ahead and created a generator that will create all the files and folder structure for us. Here is how it is done.
Generate the Generator
Rails has a generator to generate a generators . That was difficult. ;)
rails generate generator vue
This will create a file structure like this.
Let’s know what each file is about.
- USAGE - This file gives useful hints and help when we run the help command on any generator. In our case if we run
rails g vue --helpit will show us all the helpful details. We will look into the content of the file in a while.
- vue_generator.rb - This is the main file where all our logic lives. The interesting thing about this file is that when we call generator all the public method in this files are called in the order of their definition.
- templates - It is the directory where we define template for all the files that we are going to generate. We will understand this better as we see the source code.
Vue Generator Source Code
Here is how our
USAGE file looks like.
Here is how running the help command will look like.
Here is our
All the templates below are ERB files which allow us to use methods and variable to create custom content.
That is all the thing required to create a generator in Rails. Let’s see an example and what files are generated.
as we can see the specified three files have been generated. Let’s checkout their content.
And all these files are created perfectly namespaced for us.
I hope it was fun reading this article. If you have any suggestions do let me know in the comments below. I would love to take up the next challenge and put this generator into a gem. Let’s see how that goes. Thanks for reading. :)