File: component_generator.rb

package info (click to toggle)
ruby-view-component 2.74.1-1
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm
  • size: 3,156 kB
  • sloc: ruby: 6,731; sh: 163; javascript: 10; makefile: 4
file content (46 lines) | stat: -rw-r--r-- 1,451 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
# frozen_string_literal: true

require "rails/generators/abstract_generator"

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

      source_root File.expand_path("templates", __dir__)
      argument :attributes, type: :array, default: [], banner: "attribute"
      class_option :sidecar, type: :boolean, default: false

      def create_locale_file
        if ViewComponent::Base.config.generate.distinct_locale_files
          I18n.available_locales.each do |locale|
            create_file destination(locale), translations_hash([locale]).to_yaml
          end
        else
          create_file destination, translations_hash(I18n.available_locales).to_yaml
        end
      end

      private

      def translations_hash(locales = [:en])
        locales.map { |locale| [locale.to_s, translation_keys] }.to_h
      end

      def translation_keys
        keys = attributes.map(&:name)
        keys = %w[hello] if keys.empty?
        keys.map { |name| [name, name.capitalize] }.to_h
      end

      def destination(locale = nil)
        extention = ".#{locale}" if locale
        if sidecar?
          File.join(component_path, class_path, "#{file_name}_component", "#{file_name}_component#{extention}.yml")
        else
          File.join(component_path, class_path, "#{file_name}_component#{extention}.yml")
        end
      end
    end
  end
end