Rails:使用脚手架生成HTML和JS视图

时间:2013-05-01 15:14:51

标签: ruby-on-rails view generator

我已阅读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文件会怎么样?

2 个答案:

答案 0 :(得分: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视图。

答案 1 :(得分: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文件。