So far if you create a Rails app, you know that it can quickly to do things like:
- Add RSpec and Cucumber.
- Disable/turn off Test Unit.
- Switch the default database engine to PostgreSQL.
- Add other Gems such as HAML, CoffeeScript, …
Luckily we can customize what the Rails app generator generates. In this article, I will use Rails app templates to customize the default behavior of the Rails application generator. Let’s run through this with me.
Rails App Templates
Rails app templates allow you to run actual commands during the generation process. For example, I want to install rspec and haml, create a readme.md file, and commit the whole thing to git. I can easily do this by creating an Rails application template. Let create a file called app_template.rb and add the codes below:
1 2 3 4 5 6 7 8 9 10
If you generate a new app with the parameters
-m app_template.rb it will run the instructions you listed in the template. The code listed above will get executed when you run the following command:
If you browse your Rails project you’ll see that rspec, haml got installed and the default readme file was removed and a readme.md file was added, and finally everything was committed to git.
In addition, you can have the application template prompt the user for more information. The code listed below allows you to do like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In the code above, the yes? function will prompt the user with a yes/no question. The ask function will prompt the user for text input. In this case, we ask the user if they wish to generate a root controller, and if they say yes, we prompt them for a name.
So far so good, That’s it! See ya!