簡體   English   中英

將哈希作為參數傳遞給Rake任務

[英]Pass Hash as Parameter to Rake Task

我有一個佣金任務

task :post_hit, [:host, :title, :description, :model, :num_assignments, :reward, :lifetime, :qualifications, :p, :opts] => :environment do |t, args|

:p需要是一個哈希,但如果我嘗試:

rake turkee:post_hit["http://www.staging.collegesportsbluebook.com","LS Info","Fill In Player First Name","MechanicalTurk",100,0.01,2,{},{id: 5},{}]

它錯誤地說id:無法解析(空間似乎做了什么)。

如果我試過:

rake turkee:post_hit["http://www.staging.collegesportsbluebook.com","LS Info","Fill In Player First Name","MechanicalTurk",100,0.01,2,{},{"id: 5"},{}]

字符串"id: 5"被解釋為單個字符串。

我們不允許通過哈希來耙任務嗎?

我使用類似查詢字符串的參數並使用Rack::Utils.parse_nested_query解析它們

這是我如何做到的

require 'rack/utils' # needed for Rack::Utils.parse_nested_query

namespace :foo do
  task :bar, [ :args_expr ] => :environment do |t, args|
     args.with_defaults(:args_expr => "name=abdo&fruits[]=bananas&fruits[]=dates")
     options = Rack::Utils.parse_nested_query(args[:args_expr])

     puts options
  end
end

我這樣稱它:(注意如何傳遞數組和哈希)

bundle exec rake "foo:bar[name=abdo&fruits[]=apples&fruits[]=oranges&hash[foo]=bar&hash[cool]=notmuch]"

輸出:

{"name"=>"abdo", "fruits"=>["apples", "oranges"], "hash"=>{"foo"=>"bar", "cool"=>"notmuch"}}

當您通過終端發出rake任務時,您處於UNIX或Bash環境中,因此您需要遵守該語言的規則,據我所知,該規則不包括哈希。 我可能錯了。

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html#toc5

這並不意味着編寫rake任務的人沒有做一些聰明的事情來將字符串解析為哈希。 如果我是你,並試圖找出它,我會看看源代碼,看看該rake任務如何解析它的變量。

PS。 如果它是你正在使用的gem並且你也在使用bundler,你可以發出bundle open gem_name來打開源代碼,rake任務通常以.rake結尾...

嘗試將任務中的:p變量聲明為哈希值? :p => {}

任務:post_hit,[:host,:title,:description,:model,:num_assignments,:reward,:lifetime,:qualifications,:p => {},:opts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM