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

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

我该怎么做呢?


当前回答

在上面的答案中,传递参数的方法是正确的。然而,要运行带有参数的rake任务,新版本的rails涉及到一个小技术问题

它将与rake“namespace:taskname['argument1']”一起工作

注意从命令行运行任务时使用的倒引号。

其他回答

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

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

如果你想传递命名参数(例如使用标准OptionParser),你可以使用这样的东西:

$ rake user:create -- --user test@example.com --pass 123

注意——,这是绕过标准Rake参数所必需的。应该适用于Rake 0.9。X, <= 10.3.x。

更新的Rake已经改变了对——的解析,现在你必须确保它没有传递给OptionParser#parse方法,例如使用parser.parse!(ARGV[2..-1])

require 'rake'
require 'optparse'
# Rake task for creating an account

namespace :user do |args|
  desc 'Creates user account with given credentials: rake user:create'
  # environment is required to have access to Rails models
  task :create do
    options = {}
    OptionParser.new(args) do |opts|
      opts.banner = "Usage: rake user:create [options]"
      opts.on("-u", "--user {username}","User's email address", String) do |user|
        options[:user] = user
      end
      opts.on("-p", "--pass {password}","User's password", String) do |pass|
        options[:pass] = pass
      end
    end.parse!

    puts "creating user account..."
    u = Hash.new
    u[:email] = options[:user]
    u[:password] = options[:pass]
    # with some DB layer like ActiveRecord:
    # user = User.new(u); user.save!
    puts "user: " + u.to_s
    puts "account created."
    exit 0
  end
end

exit将确保额外的参数不会被解释为Rake任务。

参数的快捷方式也可以工作:

 rake user:create -- -u test@example.com -p 123

当rake脚本看起来像这样时,也许是时候寻找另一种工具来实现这一点了。

我喜欢参数传递的“querystring”语法,特别是当有很多参数要传递时。

例子:

rake "mytask[width=10&height=20]"

“querystring”是:

width=10&height=20

警告:注意语法是rake“mytask[foo=bar]”而不是rake mytask["foo=bar"]

当在rake任务中使用Rack::Utils进行解析时。parse_nested_query,得到一个哈希值:

=> {"width"=>"10", "height"=>"20"}

(最酷的事情是你可以传递哈希和数组,更多如下)

以下是如何实现这一点:

require 'rack/utils'

task :mytask, :args_expr do |t,args|
  args.with_defaults(:args_expr => "width=10&height=10")
  options = Rack::Utils.parse_nested_query(args[:args_expr])
end

下面是我在delayed_job_active_record_threading gem中使用的一个更扩展的示例:

bundle exec rake "dj:start[ebooks[workers_number]=16&ebooks[worker_timeout]=60&albums[workers_number]=32&albums[worker_timeout]=120]"

以与上面相同的方式解析,使用环境依赖项(为了加载Rails环境)

namespace :dj do
  task :start, [ :args_expr ] => :environment do |t, args|
    # defaults here...
    options = Rack::Utils.parse_nested_query(args[:args_expr])  
  end
end

给出以下选项

=> {"ebooks"=>{"workers_number"=>"16", "worker_timeout"=>"60"}, "albums"=>{"workers_number"=>"32", "worker_timeout"=>"120"}}

在传递参数时,更好的选择是输入文件,这可以是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 

上面描述的大多数方法对我来说都不起作用,也许它们在新版本中已弃用。 最新的指南可以在这里找到:http://guides.rubyonrails.org/command_line.html#custom-rake-tasks

下面是该指南的复制粘贴示例:

task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
  # You can use args from here
end

像这样调用它

bin/rake "task_name[value 1]" # entire argument string should be quoted