我正在写一个Rake任务,我想传递一个数组作为参数之一.这是我现在的方式.
task :change_statuses,:ids,:current_status,:new_status do |task,args| puts "args were #{args.inspect}" end
我已经尝试以这些方式运行任务:
# First argument as array rake "change_statuses[[1,2,3],active,inactive]" # First argument as string rake "utility:change_account_statuses['1,3',foo,bar]"
我的预期产出是:
args were {:ids=> [1,:current_status=> 2,:new_status=> 3}
但是,我的实际输出在每种情况下是:
args were {:ids=>"[1",:current_status=>"2",:new_status=>"3]"}
如何将数组传递给Rake任务?
解决方法
灵魂之一是避免在字符串中的符号,所以您的命令行将如下所示:
$rake change_statuses['1 2 3',bar]
然后你可以简单地拆分ID:
# Rakefile task :change_statuses,args| ids = args[:ids].split ' ' puts "args were #{args.inspect}" puts "ids were #{ids.inspect}" end
或者您可以解析ids值以获得预期的输出:
args[:ids] = args[:ids].split(' ').map{ |s| s.to_i }
我使用耙子0.8.7