Rails generators are command-line tools that are used for automating the process of creating or editing files in Ruby on Rails. They can be used to save the development team time by using templates to create and automate the process of writing boilerplate code. To get a list of rails generators for a project you can run:
This also will highlight some options such as “pretend” mode which will run the generator but not make any changes. They are commonly used to create a scaffold for a new feature, create migrations, or build out controllers. You can also build out your own custom generator.
In the rails project, generators live here. The rails templates the generators use are found in generators/rails/app/templates. The .tt file format is just a Thor template file.
To create your own generator you would need to use a generator.
Open the generator that rails created lib/generators/rails/component/component_generator.rb and add methods to copy the template file to a new jsx file and add a line to application.js.
template “Component.jsx.tt”, “app/javascript/components/#{file_name.titleize}.jsx”
end
def edit_application_js_file
append_to_file(“app/javascript/application.js”, “\nimport \”./components/#{file_name.titleize}\”\n”)
end
end
Then, create the template in templates: lib/generators/rails/component/templates/Component.jsx.tt
import * as ReactDOM from ‘react-dom’
const <%= class_name %> = () => {
return (< div ><%= class_name %>< / div>)
}
export default <%= class_name %>
If you rerun rails generate you should now see your new custom generator is ready for use.
For more helpful guides and how-tos for Ruby on Rails visit our blog!