1

我已经阅读了有关generators的文档,但找不到任何有关创建视图的信息。阅读Rails 3 Generators gem 中的代码,我发现您可以通过在lib/generators/erb/scaffold/templates/. 您还可以使用以下代码段指定要在scaffold_generator.rb文件中创建的视图:

def available_views
  ['index', 'edit', 'show', 'new', '_form']
end

所以我的问题是,如果我想同时创建一个index.html.erb文件和一个index.js.erb文件怎么办?

4

2 回答 2

1

显然,视图的实际创建是由一个名为copy_view_files. 您可以在该函数中指定所需的视图类型。这样做之后,我的scaffold_generator.rb样子是这样的:

需要'rails/generators/erb/scaffold/scaffold_generator'

module Erb
  module Generators
    class ScaffoldGenerator < Erb::Generators::ScaffoldGenerator
      source_root File.expand_path(File.join('..', 'templates'), __FILE__)

      def copy_view_files
        primary_views.each do |view|
          filename = filename_with_extensions view
          template "#{view}.html.erb", File.join('app', 'views', controller_file_path, filename)
          template "#{view}.js.erb", File.join('app', 'views', controller_file_path, filename)
        end
      end

      hook_for :form_builder, :as => :scaffold

      protected
        def primary_views
          ['index', 'edit', 'show', 'new']
        end

        def handler
          :erb
        end
    end
  end
end

请注意,在copy_view_files函数中,有两次调用template. 第一个创建了一组 html 视图,而第二个创建了我想要的 js 视图。

于 2013-05-01T18:01:05.170 回答
0

我对问题https://stackoverflow.com/a/62441675/385730发布了类似的答案。

您可以覆盖脚手架生成器lib/rails/generators/erb/scaffold/scaffold_generator.rb文件。

第 1 步: 复制最新scaffold_generator.rb文件。

mkdir -p lib/rails/generators/erb/scaffold && cp $(bundle show railties)/lib/rails/generators/erb/scaffold/scaffold_generator.rb lib/rails/generators/erb/scaffold/

第 2 步: 添加自定义代码以生成.js.erb您想要的文件。

# frozen_string_literal: true

require "rails/generators/erb"
require "rails/generators/resource_helpers"

module Erb # :nodoc:
  module Generators # :nodoc:
    class ScaffoldGenerator < Base # :nodoc:
      include Rails::Generators::ResourceHelpers

      argument :attributes, type: :array, default: [], banner: "field:type field:type"

      def create_root_folder
        empty_directory File.join("app/views", controller_file_path)
      end

      def copy_view_files
        available_views.each do |view|
          formats.each do |format|
            filename = filename_with_extensions(view, format)
            template filename, File.join("app/views", controller_file_path, filename)
          end
        end
        javascript_views.each do |view|
          path = File.join('app', 'views', controller_file_path, "#{view}.js.erb")
          File.open(path, "w")
        end  
      end

    private

      def available_views
        %w(index edit show new _form)
      end

      def javascript_views
        %w(index show create update)
      end

    end
  end
end

现在,当您运行脚手架生成器时,您将看到.js.erb创建的新文件。

于 2020-06-18T03:07:13.870 回答