Creating a Rails generator
Here is a simple example that works with rails 6.1.
First create the generator scaffold:
» bin/rails generate generator stimulus_controller
create lib/generators/stimulus_controller
create lib/generators/stimulus_controller/stimulus_controller_generator.rb
create lib/generators/stimulus_controller/USAGE
create lib/generators/stimulus_controller/templates
invoke test_unit
create test/lib/generators/stimulus_controller_generator_test.rb
This already gives you something for free:
» bin/rails generate stimulus_controller --help
Usage:
rails generate stimulus_controller NAME [options]
The contents of the help message are defined in the USAGE
file, that you can update to something like this:
Description:
Creates a stimulus controller
Example:
bin/rails generate stimulus_controller thing
This will create:
app/javascript/controllers/thing_controller.js
Now you can edit lib/generators/stimulus_controller/stimulus_controller_generator.rb
. All public methods of this class will be executed in the order of definition.
class StimulusControllerGenerator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
def create_js_file
template "controller.js", "app/javascript/controllers/#{name}_controller.js"
end
end
And define the template as lib/generators/stimulus_controller/templates/controller.js
:
import { Controller } from "stimulus"
export default class extends Controller {
// static targets = []
// static classes = []
// static values = {}
//
// connect() {}
}
Links
The official documentation is very good: