ライブラリ > optparse

optparse

  • 簡単にオプションの解析が出来る。
  • CUIベースのプログラムをする際に便利

例:

+ コード
require 'optparse'
 
class CheckOption
 
  attr_reader :username
  attr_reader :password
  attr_reader :title
  attr_reader :content
  attr_reader :file
 
  def initialize
    @username = nil
    @password = nil
    @title = nil
    @content = nil
    @file = nil
 
    @option_parser = OptionParser.new
    #ここから
    @option_parser.version = "0.0.1"            #こうしとくと、--versionと引数にあるとこの値を表示してくれる。
    @option_parser.on('-u username'){|value| @username = value}
    @option_parser.on('-p password'){|value| @password = value}
    @option_parser.on('-t title'){|value| @title = value}
    @option_parser.on('-c content'){|value| @content = value}
    @option_parser.on('-f content file'){|value| @file = value}        #-f hoge.txtと引数にあった時valueがhoge.txtなので、@fileに入る!
    #ここまでがおまじない(オプションを追加)
  end
 
  def check
    if ARGV[0].nil?
      p "no option"
      return false
    end
    begin
      @option_parser.parse(ARGV)           #解析はココ
    rescue
      p "option error"
    end
 
    if(@username == nil || @password  == nil ||  @title == nil)
      p "not enough options"
      return false
    end
 
    if(@content == nil && @file == nil)
      p "content or file is nothing"
      return false
    end
  end
 
end
 

上記のようなコードの時、以下のように使えます。
+ コード
arguments = CheckOption.new
exit unless arguments.check
 
なんか処理
 



名前:
コメント:
最終更新:2008年07月01日 21:18