如何为播种设置 Rake 任务 [英] How to set up a Rake task for seeding

查看:54
本文介绍了如何为播种设置 Rake 任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这确实是一个关于 Rake & Rails & 依赖项的新手问题.试图让我了解所有这些是如何组合在一起的)

(This is really a newbie question about Rake & Rails & dependencies in general. Trying to wrap my head around how all this fits together)

基本上,我想要一个 Rake 任务,它的作用类似于 seed.rb,但被单独调用.它添加了开发环境的测试数据,而我的seed.rb提供了所有环境的基础数据.

Basically, I want a Rake task that acts like seed.rb but is called separately. It adds test data for the development environment, while my seed.rb provides basic data for all environments.

脚本family_seed.rb 使用FactoryGirl 生成一些记录.它看起来像这样:

The script, family_seed.rb, uses FactoryGirl to generate some records. It looks like this:

require File.expand_path('../../config/environment', __FILE__)
require './spec/factories'

Family.delete_all
Member.delete_all
zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')

它与 bundle exec "ruby db/family_seeds.rb" 一起运行良好,但我的问题是如何使用 Rake 设置它.整个事情应该放在一个 Rake 任务中吗?相反,我如何设置一个调用脚本的任务,同时确保 Rails 开发环境在运行时可用?我不仅要努力完成工作,还要以正确"的方式去做.

It runs fine with bundle exec "ruby db/family_seeds.rb", but my question is how to set it up with Rake. Should the whole thing be placed inside a Rake task? How could I, instead, set up a task that would call the script, while ensuring that the Rails development environment is available when it runs? I'm trying not just to get the job done, but to do it in a "right" way.

推荐答案

解决这个问题的一种方法是在 lib 中创建一个类或模块(这样可以更容易地编写测试,并使代码更可重用):

One way to approach this would be to create a class or module in lib (this makes it easier to write tests for, and makes the code more reusable):

require '../spec/factories'

class FamilySeed

  def self.seed
    raise "Don't run this in production!" if Rails.env.production?

    Family.delete_all
    Member.delete_all
    zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
    blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')
  end

end

如何创建rake任务:

require 'family_seed'

namespace :seed do
  task :families => :environment do
    FamilySeed.seed
  end
end

我会小心允许诸如 Family.delete_all 和 Member.delete_all 之类的东西过于自由地使用.稍后,您可以通过在生产数据库上调用您不想要的东西来轻松地对自己开枪.

I'd be careful with allowing things like Family.delete_all and Member.delete_all to be too freely used. You could easily shoot yourself in the foot later on by calling something you didn't mean to on a production db.

在您的命令中运行它,如下所示:

Run it in your command like with the following:

bundle exec rake seed:families

这篇关于如何为播种设置 Rake 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆