2012-10-13 48 views
0

我正在使用Ruby的optparse庫來解析我的命令行應用程序的選項,但我無法弄清楚如何接受命令。如何將optparse配置爲接受兩個參數選項作爲命令?

這將是這樣的:

commit -f -d init 

init會在這種情況下命令。它並不總是必需的,因爲如果用戶沒有提供任何應該運行的默認命令。

這裏是我到現在爲止代碼:

OptionParser.new do |opts| 
    opts.banner = %Q!Usage: 
    pivotal_commit           # to commit with a currently started issue 
    pivotal_commit -f          # to commit with a currently started issue and finish it 
    pivotal_commit -d          # to commit with a currently started issue and deliver it 
    pivotal_commit init -e "[email protected]" -p my_password -l #to generate a config file at the current directory! 

    opts.on("-e", "--email [EMAIL]", String, "The email to the PT account you want to access") do |v| 
    options[:email] = v 
    end 

    opts.on("-p", "--password [PASSWORD]", String, "The password to the PT account you want to access") do |v| 
    options[:password] = v 
    end 

    opts.on("-f", '--finish', 'Finish the story you were currently working on after commit') do |v| 
    options[:finish] = v 
    end 

    opts.on('-d', '--deliver', 'Deliver the story you were currently working on after commit') do |v| 
    options[:deliver] = v 
    end 

    opts.on_tail('-h', '--help', 'Show this message') do 
    puts opts 
    exit 
    end 

    opts.on_tail('-v', '--version', 'Show version') do 
    puts "pivotal_committer version: #{PivotalCommitter::VERSION}" 
    exit 
    end 

end.parse! 

回答

5

命令行參數(不是期權)是ARGVARGV調用OptionParser#parse!因爲#parse!提取選項之後。 所以,你可以得到子是這樣的:

options = {} 

OptionParser.new do |opts| 
# definitions of command-line options... 
# ... 
end.parse! 

subcommand = ARGV.shift || "init" 

print "options: " 
p options 
puts "subcommand: #{subcommand}" 

如果你有許多子命令,Thor寶石可以幫助你。

而且,雖然這不是您的問題的答案,但選項定義中的括號([])表示該選項的參數是可選的。 例如,在您的定義,電子郵件地址和密碼可能是零甚至當選項傳遞:

$ pivotal_commit -e 
options: {:email=>nil} 
subcommand: init 

如果當選項傳遞需要的參數,去掉括號:

# ... 
    opts.on("-e", "--email EMAIL", String, "The email to the PT account you want to access") do |v| 
    options[:email] = v 
    end 
# ... 

現在的說法需要電子郵件:

$ pivotal_commit -e 
pivotal_commit:6:in `<main>': missing argument: -e (OptionParser::MissingArgument) 
相關問題