File: stimulus_generator.rb

package info (click to toggle)
ruby-view-component 4.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 472 kB
  • sloc: ruby: 2,278; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,260 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

require "generators/view_component/abstract_generator"

module ViewComponent
  module Generators
    class StimulusGenerator < ::Rails::Generators::NamedBase
      include ViewComponent::AbstractGenerator

      source_root File.expand_path("templates", __dir__)
      class_option :sidecar, type: :boolean, default: false
      class_option :typescript, type: :boolean, default: false

      def create_stimulus_controller
        template "component_controller.#{filetype}", destination
      end

      def stimulus_module
        return "stimulus" if legacy_stimulus?

        "@hotwired/stimulus"
      end

      private

      def filetype
        typescript? ? "ts" : "js"
      end

      def destination
        if sidecar?
          File.join(component_path, class_path, "#{file_name}_component", "#{file_name}_component_controller.#{filetype}")
        else
          File.join(component_path, class_path, "#{file_name}_component_controller.#{filetype}")
        end
      end

      def legacy_stimulus?
        package_json_pathname = Rails.root.join("package.json")
        package_json_pathname.exist? && JSON.parse(package_json_pathname.read).dig("dependencies", "stimulus").present?
      end
    end
  end
end