Rails生成器:传递一个参数数组

7

我已经查看了关于如何创建自己的生成器的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 %>

我该如何编写生成器以使用多个参数并基于这些参数生成多行?
1个回答

0
构建表单生成器:$ rails g generator form
# lib/generators/form/form_generator.rb
class FormGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('templates', __dir__)

  argument :model_name, type: :string, default: 'demo'
  class_option :attributes, type: :hash, default: {}

  def build_form
    create_file "app/views/#{model_name.pluralize}/_form.html.erb", 
    "<%= simple_form_for @#{model_name.pluralize} do | f | %>" + "\n" +
    options.attributes.map { |attribute, type|
      "<%= f.#{type}  :#{attribute}, label: '#{attribute}' %> \n"
    }.join('') +
    "<% end %>"
  end
end

测试

$ rails g form demo --attributes name:input, pass:input, remember_me:check_box

结果

# app/views/demos/_form.html.erb
<%= simple_form_for @demos do | f | %>
<%= f.input,  :name, label: 'name' %> 
<%= f.input,  :pass, label: 'pass' %> 
<%= f.check_box  :remember_me, label: 'remember_me' %> 
<% end %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接