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

Nil*_*ngh 1 ruby-on-rails generator scaffold

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

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

rails g scaffold model 
Run Code Online (Sandbox Code Playgroud)

我曾尝试将文件添加到 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
Run Code Online (Sandbox Code Playgroud)

但是在这方面我什么都不需要帮助,我需要覆盖什么文件以及我需要放置在哪里。

Ank*_*itG 5

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

 ~/D/p/p/generator_test> tree lib/
lib/
??? assets
??? tasks
??? templates #<========
    ??? active_record
        ??? model
            ??? model.rb
Run Code Online (Sandbox Code Playgroud)

这是我的自定义模板

<% 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 -%>
Run Code Online (Sandbox Code Playgroud)

跑步脚手架

rails g scaffold property

文件已创建

class Property < ApplicationRecord

   before_save :my_custom_method

   # my method
   def my_custom_method

   end

end
Run Code Online (Sandbox Code Playgroud)