install_generator.rb 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# frozen_string_literal: true

require "pathname"
require "json"

module ActionText
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      source_root File.expand_path("templates", __dir__)

      def install_javascript_dependencies
12
        template "#{GEM_ROOT}/../railties/lib/rails/generators/rails/app/templates/bin/yarn.tt",
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
                 "bin/yarn"

        say "Installing JavaScript dependencies"
        run "yarn add #{js_dependencies.map { |name, version| "#{name}@#{version}" }.join(" ")}",
          abort_on_failure: true, capture: true
      end

      def append_dependencies_to_package_file
        app_javascript_pack_path = Pathname.new("app/javascript/packs/application.js")

        if app_javascript_pack_path.exist?
          js_dependencies.keys.each do |name|
            line = %[require("#{name}")]

            unless app_javascript_pack_path.read.include? line
              say "Adding #{name} to #{app_javascript_pack_path}"
              append_to_file app_javascript_pack_path, "\n#{line}"
            end
          end
        else
          warn <<~WARNING
            WARNING: Action Text can't locate your JavaScript bundle to add its package dependencies.

            Add these lines to any bundles:

            require("trix")
            require("@rails/actiontext")

            Alternatively, install and setup the webpacker gem then rerun `bin/rails action_text:install`
            to have these dependencies added automatically.
          WARNING
        end
      end

      def create_actiontext_files
        template "actiontext.scss", "app/assets/stylesheets/actiontext.scss"

50
        copy_file "#{GEM_ROOT}/app/views/active_storage/blobs/_blob.html.erb",
51 52 53 54 55 56 57 58 59
                  "app/views/active_storage/blobs/_blob.html.erb"
      end

      def create_migrations
        run "rake active_storage:install:migrations"
        run "rake railties:install:migrations"
        run "rake action_text:install:migrations"
      end

60 61 62
      hook_for :test_framework

      private
V
Vinicius Stock 已提交
63
        GEM_ROOT = "#{__dir__}/../../../.."
64

V
Vinicius Stock 已提交
65 66 67
        def js_dependencies
          package_contents = File.read(Pathname.new("#{GEM_ROOT}/package.json"))
          js_package = JSON.load(package_contents)
68

V
Vinicius Stock 已提交
69 70 71
          js_package["peerDependencies"].dup.merge \
            js_package["name"] => "^#{js_package["version"]}"
        end
72 73 74
    end
  end
end