我已经查看了关于如何创建自己的生成器的rails casts,并阅读了许多堆栈溢出的问题。基本上,我要做的是构建一个生成器,就像内置的rails迁移生成器一样,它接受像attribute:type
这样的参数,然后根据需要插入它们。下面是我现在为我的生成器编写的代码。
class FormGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :model_name, :type => :string
argument :attributes, type: :array, default: [], banner: "attribute:input_type attribute:input_type"
argument :input_types, type: :array, default: [], banner: "attribute:input_type attribute:input_type"
def create_form_file
create_file "app/views/#{model_name.pluralize}/_form.html.erb", "
<%= simple_form_for @#{model_name.pluralize} do | f | %>
<%= f.#{input_type} :#{attribute}, label: '#{attribute}' %>
<% end %>
"
end
end
我想让它生成一个视图文件,其中行数与参数数量相同。因此,通过传递 rails g form products name:input amount:input other_attribute:check_box
将生成一个名为_form.html.erb
的文件,其内容如下:
<%= simple_form_for @products do | f | %>
<%= f.input :name, label: 'name' %>
<%= f.input :amount, label: 'amount' %>
<%= f.check_box :other_attribute, label: 'other_attribute' %>
<% end %>
我该如何编写生成器以使用多个参数并基于这些参数生成多行?