我有一个rake任务,需要将一个值插入多个数据库。

我想从命令行或从另一个rake任务中将这个值传递给rake任务。

我该怎么做呢?


当前回答

在传递参数时,更好的选择是输入文件,这可以是excel, json或任何你需要的,从那里读取数据结构和你需要的变量,包括变量名,因为是需要的。 读取文件可以有以下结构。

  namespace :name_sapace_task do
    desc "Description task...."
      task :name_task  => :environment do
        data =  ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
    # and work whit yoour data, example is data["user_id"]

    end
  end

示例json

{
  "name_task": "I'm a task",
  "user_id": 389,
  "users_assigned": [389,672,524],
  "task_id": 3
}

执行

rake :name_task 

其他回答

除了kch的回答(我不知道如何留下评论,对不起):

在rake命令之前,您不必将变量指定为ENV变量。你可以像设置命令行参数一样设置它们:

rake mytask var=foo

然后从rake文件中访问这些ENV变量,就像这样:

p ENV['var'] # => "foo"

另一个常用的选项是传递环境变量。在你的代码中,你可以通过ENV['VAR']读取它们,并且可以在rake命令之前传递它们,比如

$ VAR=foo rake mytask

选项和依赖项需要在数组中:

namespace :thing do
  desc "it does a thing"
  task :work, [:option, :foo, :bar] do |task, args|
    puts "work", args
  end
  
  task :another, [:option, :foo, :bar] do |task, args|
    puts "another #{args}"
    Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
    # or splat the args
    # Rake::Task["thing:work"].invoke(*args)
  end

end

Then

rake thing:work[1,2,3]
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

rake thing:another[1,2,3]
=> another {:option=>"1", :foo=>"2", :bar=>"3"}
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

注意:变量任务是任务对象,除非你知道/关心Rake内部,否则没有多大帮助。

RAILS的注意:

如果从Rails运行任务,最好通过添加=> [:environment]来预加载环境,这是一种设置依赖任务的方法。

  task :work, [:option, :foo, :bar] => [:environment] do |task, args|
    puts "work", args
  end

我只是想能够奔跑:

$ rake some:task arg1 arg2

简单,是吧?(不!)

Rake将arg1和arg2解释为任务,并尝试运行它们。所以我们要赶在它之前中止。

namespace :some do
  task task: :environment do
    arg1, arg2 = ARGV

    # your task...

    exit
  end
end

听着,括号!

免责声明:我希望能够在一个相当小的宠物项目中做到这一点。不打算用于“真实世界”,因为您失去了链耙任务的能力(即耙task1 task2 task3)。我觉得不值得。只需使用丑陋的rake任务[arg1,arg2]。

desc 'an updated version'
task :task_name, [:arg1, :arg2] => [:dependency1, :dependency2] do |t, args|
    puts args[:arg1]
end