Rails - Customize And Improve Your Generators
In our day to day web-application development, we use different Rails built in generators like,
rails g controller users rails g model User ...
Look how many files are generated when you create a controller.
So basically, it will create
- View helper file
- stylesheet file in assets
- test files in test directory
They have some default types and extensions. like,
- Script file is always coffee script
- Test cases is default to Test::Unit.
- CSS is default to scss
- HTML template is always
In this blog post, we are going to customise all these defaults and will get some overview of each generator’s customisation one by one.
If there are multiple customisation options to override then you can use block like given below,
Don’t worry about the code inside, we will go through different config options now.
You can use this to change the default type of JS file which is coffee-script by default. For example, if you don’t want to use coffeescript then add below line in your application.rb
If you have Rspec already installed in your application and now you want to change the test framework to use Test::Unit without removing Rspec then just add below line.
If you don’t want to generate test files for views then just add views: false in above config.
If you don’t want to create a stylesheet file everytime while creating a controller just set this value to false.
Same as we did for stylesheet, can turn off creating the JS files for each controller
You can customize your template engine for haml and slim instead of Ruby.
You can also change the ORM Mapping for active_record with some other options.
Here is how I customise my generators
and if you try again generating controller with above config,
You can see that it creates Rspec files for test cases, normal JS file instead of coffee script and it also skips creating a CSS file.
We can create our own generators in Rails using generators, will see in the next post. So stay in touch.!!
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management