我正在尝试自定义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
但是在这方面我无需帮助,我需要覆盖哪些文件以及我需要放在哪里。
答案 0 :(得分:1)
以下是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
答案 1 :(得分:1)
为简化起见,您可以使用以下命令将所有ActiveRecord模型模板复制到当前的Rails项目中:
mkdir -p lib/templates/active_record/model && \
cp $(bundle show activerecord)/lib/rails/generators/active_record/model/templates/* lib/templates/active_record/model