From 5720248c363bee0f1bdd8eeb06e42c742da263b8 Mon Sep 17 00:00:00 2001 From: eelco Date: Sun, 1 Dec 2024 19:17:17 +0100 Subject: [PATCH] Optionally inherit from ApplicationController --- lib/generators/stimulus/stimulus_generator.rb | 16 ++++++++++++++++ .../stimulus/templates/controller.js.tt | 6 +++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/generators/stimulus/stimulus_generator.rb b/lib/generators/stimulus/stimulus_generator.rb index 5af2437..093f085 100644 --- a/lib/generators/stimulus/stimulus_generator.rb +++ b/lib/generators/stimulus/stimulus_generator.rb @@ -19,4 +19,20 @@ def controller_name def stimulus_attribute_value(controller_name) controller_name.gsub(/\//, "--").gsub("_", "-") end + + def controller_import + if application_controller_exists? + 'import ApplicationController from "./application_controller"' + else + 'import { Controller } from "@hotwired/stimulus"' + end + end + + def parent_controller + application_controller_exists? ? "ApplicationController" : "Controller" + end + + def application_controller_exists? + File.exist?(Rails.root.join("app/javascript/controllers/application_controller.js")) + end end diff --git a/lib/generators/stimulus/templates/controller.js.tt b/lib/generators/stimulus/templates/controller.js.tt index 62b20fa..6969f77 100644 --- a/lib/generators/stimulus/templates/controller.js.tt +++ b/lib/generators/stimulus/templates/controller.js.tt @@ -1,7 +1,7 @@ -import { Controller } from "@hotwired/stimulus" +<%= controller_import %> -// Connects to data-controller="<%= @attribute %>" -export default class extends Controller { +// Connects to data-controller="<%= attribute %>" +export default class extends <%= parent_controller %> { connect() { } }