File: preview_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 (39 lines) | stat: -rw-r--r-- 1,290 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
# frozen_string_literal: true

module ViewComponent
  module Generators
    class PreviewGenerator < ::Rails::Generators::NamedBase
      source_root File.expand_path("templates", __dir__)
      class_option :preview_path, type: :string, desc: "Path for previews, required when multiple preview paths are configured", default: ViewComponent::Base.config.generate.preview_path

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

      def create_preview_file
        preview_paths = ViewComponent::Base.config.previews.paths
        optional_path = options[:preview_path]
        return if preview_paths.count > 1 && optional_path.blank?

        path_prefix = if optional_path.present?
          optional_path
        else
          preview_paths.one? ? preview_paths.first : "test/components/previews"
        end

        template "component_preview.rb", File.join(path_prefix, class_path, "#{file_name}_component_preview.rb")
      end

      private

      def file_name
        @_file_name ||= super.sub(/_component\z/i, "")
      end

      def render_signature
        return if attributes.blank?

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