2012-10-13 4 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

명령 줄 인수 (안 옵션) ARGV에서 OptionParser#parse!#parse! 때문에 추출 옵션을 호출 한 후 ARGV에 있습니다

다음은 지금의로이 코드입니다. 그래서, 당신은 다음과 같은 하위 명령을 얻을 수 있습니다 : 당신이 많은 하위 명령이있는 경우

options = {} 

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

subcommand = ARGV.shift || "init" 

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

Thor 보석 당신을 도울 수 있습니다.

그리고이 질문에 대한 대답은 아니지만 옵션 정의에서 대괄호 ([])는 옵션의 인수가 선택 사항임을 의미합니다. 당신의 정의, 이메일과 비밀번호에 예를 들어 은 옵션이 전달되는 경우에도 nil을 수 있습니다 :

이제
# ... 
    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 
options: {:email=>nil} 
subcommand: init 

이메일 :

$ pivotal_commit -e 
pivotal_commit:6:in `<main>': missing argument: -e (OptionParser::MissingArgument) 
관련 문제