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

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

我该怎么做呢?


当前回答

如果你想传递命名参数(例如使用标准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"}}

我不知道如何传递args和:environment,直到我解决了这个问题:

namespace :db do
  desc 'Export product data'
  task :export, [:file_token, :file_path] => :environment do |t, args|
    args.with_defaults(:file_token => "products", :file_path => "./lib/data/")

       #do stuff [...]

  end
end

然后我这样调用:

rake db:export['foo, /tmp/']

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

$ VAR=foo rake mytask

如果你懒得记参数位置是什么你想做一些类似ruby参数哈希的东西。您可以使用一个参数传入一个字符串,然后将该字符串正则化为一个选项散列。

namespace :dummy_data do
  desc "Tests options hash like arguments"
  task :test, [:options] => :environment do |t, args|
    arg_options = args[:options] || '' # nil catch incase no options are provided
    two_d_array = arg_options.scan(/\W*(\w*): (\w*)\W*/)
    puts two_d_array.to_s + ' # options are regexed into a 2d array'
    string_key_hash = two_d_array.to_h
    puts string_key_hash.to_s + ' # options are in a hash with keys as strings'
    options = two_d_array.map {|p| [p[0].to_sym, p[1]]}.to_h
    puts options.to_s + ' # options are in a hash with symbols'
    default_options = {users: '50', friends: '25', colour: 'red', name: 'tom'}
    options = default_options.merge(options)
    puts options.to_s + ' # default option values are merged into options'
  end
end

在命令行中。

$ rake dummy_data:test["users: 100 friends: 50 colour: red"]
[["users", "100"], ["friends", "50"], ["colour", "red"]] # options are regexed into a 2d array
{"users"=>"100", "friends"=>"50", "colour"=>"red"} # options are in a hash with keys as strings
{:users=>"100", :friends=>"50", :colour=>"red"} # options are in a hash with symbols
{:users=>"100", :friends=>"50", :colour=>"red", :name=>"tom"} # default option values are merged into options

如果你想传递命名参数(例如使用标准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脚本看起来像这样时,也许是时候寻找另一种工具来实现这一点了。