보통 콘솔 프로그램을 만들면 usage를 출력하는 메소드를 하나씩 만들게 된다.

전달인자 받는 프로그램에서는 거의 필수라고 할 수 있는데, 루비는 이 정보를 주석에서 따와서 출력해주는 기능을 지원한다.

(개인적으로는 엄청난 혁신인 것 같다. So Cool!!)

 

# == Synopsis
#
# Display the current date and time, optionally honoring
# a format string.
#
# == Usage
#
#
#  ruby showtime.rb [ -h |  --help] [ -f |  --fmt fmtstring]
#
# fmtstring::
#   A +strftime+ format string controlling the display of the date and time.
#   If ommitted, use "%Y-%M-%d %H:%m"
#
# == Author
# Dave Thomas, The Pragmatic Programmers, LLC
#
# == Copyright
# Copyright (c) 2004 The Pragmatic Programmers.
# Licensed under the same terms as Ruby 

require 'optparse'
require 'rdoc/usage' 

fmt = "%Y-%M-%d %H:%m"
opts = OptionParser.new
opts.on("-h", "--help") { RDoc::usage }
opts.on("-f", "--fmt FMTSTRING") {|str| fmt = str }
opts.parse(ARGV) rescue RDoc::usage('usage') 

puts Time.now.strftime(fmt)

주석 내용은 당연히 RDoc 를 만들면 해당 문서에 이쁘게 박혀 나온다.

 

그럼 위의 프로그램을 –-help 인자를 주고 실행시켜보자.

 그리고 전달인자를 일부러 틀리게 실행시키면…

아… 좋다. 이제 print_usage 메서드를 따로 만들지 않아도 된다.

참고로, RDoc::usage 메서드를 사용하면 메시지 출력 후 프로그램이 종료된다.

이 때, 종료시키고 싶지 않으면 RDoc::usage_no_exit 메서드를 사용한다.

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Heart