File: component_generator.rb

package info (click to toggle)
ruby-view-component 4.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,832 kB
  • sloc: ruby: 8,385; sh: 166; makefile: 4
file content (80 lines) | stat: -rw-r--r-- 2,411 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# frozen_string_literal: true

require "generators/view_component/abstract_generator"

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

      source_root File.expand_path("templates", __dir__)

      argument :attributes, type: :array, default: [], banner: "attribute"
      check_class_collision suffix: "Component"

      class_option :call, type: :boolean, default: false
      class_option :inline, type: :boolean, default: false
      class_option :locale, type: :boolean, default: ViewComponent::Base.config.generate.locale
      class_option :parent, type: :string, desc: "The parent class for the generated component"
      class_option :preview, type: :boolean, default: ViewComponent::Base.config.generate.preview
      class_option :sidecar, type: :boolean, default: false
      class_option :stimulus, type: :boolean,
        default: ViewComponent::Base.config.generate.stimulus_controller
      class_option :skip_suffix, type: :boolean, default: false

      def create_component_file
        template "component.rb", File.join(component_path, class_path, "#{file_name}#{"_component" unless options[:skip_suffix]}.rb")
      end

      hook_for :test_framework

      hook_for :preview, type: :boolean

      hook_for :stimulus, type: :boolean

      hook_for :locale, type: :boolean

      hook_for :template_engine do |instance, template_engine|
        instance.invoke template_engine, [instance.name]
      end

      private

      def parent_class
        return options[:parent] if options[:parent]

        ViewComponent::Base.config.generate.parent_class || default_parent_class
      end

      def initialize_signature?
        initialize_signature.present?
      end

      def initialize_signature
        return if attributes.blank?

        attributes.map { |attr| "#{attr.name}:" }.join(", ")
      end

      def initialize_body
        attributes.map { |attr| "@#{attr.name} = #{attr.name}" }.join("\n    ")
      end

      def initialize_call_method_for_inline?
        options["call"]
      end

      def inline_template?
        options["inline"]
      end

      def template_engine
        options["template_engine"]
      end

      def default_parent_class
        defined?(ApplicationComponent) ? ApplicationComponent : ViewComponent::Base
      end
    end
  end
end