如何编辑 Rails 脚手架模型生成器

How to Edit Rails Scaffold Model generator

我正在尝试自定义 rails 默认脚手架生成器。对于视图,我可以通过简单地在以下位置添加文件来做到这一点:lib/templates/erb/scaffold/

这里我添加了index.html.erb并自定义了,但是我想更改这个命令生成的模型:

rails g scaffold model 

我尝试将文件添加到 lib/templates/rails/model/model_generator.rb

使用这样的代码:

 module Rails
    module Generators
      class ModelGenerator < NamedBase #metagenerator
        argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
        hook_for :orm, :required => true

      end
    end
  end

但它什么也没做我需要这方面的帮助我需要覆盖什么文件以及我需要放在哪里。

这是 Activerecord 模板。你需要把它放在 lib/templates/active_record/model/model.rb 作为

 ~/D/p/p/generator_test> tree lib/
lib/
├── assets
├── tasks
└── templates #<========
    └── active_record
        └── model
            └── model.rb

这是我的自定义模板

<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>

   #custom method start
   before_save :my_custom_method

   # my method
   def my_custom_method

   end
   #custom method end

<% attributes.select(&:reference?).each do |attribute| -%>
  belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %>
<% end -%>
<% attributes.select(&:token?).each do |attribute| -%>
  has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %>
<% end -%>
<% if attributes.any?(&:password_digest?) -%>
  has_secure_password
<% end -%>
end
<% end -%>

运行脚手架

rails g scaffold property

已创建文件

class Property < ApplicationRecord

   before_save :my_custom_method

   # my method
   def my_custom_method

   end

end

为简化起见,您可以使用以下命令将所有 ActiveRecord 模型模板复制到当前的 Rails 项目中:

mkdir -p lib/templates/active_record/model && \
cp $(bundle info activerecord --path)/lib/rails/generators/active_record/model/templates/* lib/templates/active_record/model