我使用此代码创建db记录。我如何缩小代码并使用数组只调用一个方法?
create_acquirers(args[:count_to_create].to_i)
create_companies(args[:count_to_create].to_i)
create_merchant_users(args[:count_to_create].to_i)
def create_acquirers(n)
puts ">> Creating acquirers..."
n.times { create(:acquirer) }
end
def create_companies(n)
puts ">> Creating companies..."
n.times { create(:fake_company) }
end
def create_merchant_users(n)
puts ">> Creating merchant users..."
n.times { create(:fake_merchant_user) }
end
答案 0 :(得分:1)
你不能只迭代符号(我设想的模型名称),就像这样:
populate_db(args[:count_to_create].to_i)
def populate_db(count_to_create)
[:acquirer, :fake_company, :fake_merchant_user].each do |model_name|
puts ">> Creating #{model_name.to_s.pluralize.humanize}..."
count_to_create.times { create(model_name) }
end
end
我建议将该数组拆分为方法或常量:
def populate_db(count_to_create)
model_names.each do |model_name|
puts ">> Creating #{model_name.to_s.pluralize.humanize} users..."
count_to_create.times { create(model_name) }
end
end
def model_names
[:acquirer, :fake_company, :fake_merchant_user]
end