timelogを本物のツールに
自分のコンピューターでは、プログラムはターミナルから起動します:timelog add "ProjectX" --from 08:30。プログラム名のあとに書いたものは、すべて文字列の配列としてARGVに入ります。これをきれいに解析するには、標準ライブラリのOptionParserが便利です。ここでは、自分で用意した配列で練習しましょう:
require "optparse"
argv = ["report", "--week", "--format", "csv"]
options = { format: "text", week: false }
parser = OptionParser.new do |p|
p.banner = "Usage: timelog COMMAND [options]"
p.on("--week", "this week only") { options[:week] = true }
p.on("--format FORMAT", "text or csv") { |f| options[:format] = f }
end
rest = parser.parse(argv)
[options, rest]parseはオプションを抜き出して、残ったものを返します。ここではコマンドの"report"です。おまけに、説明文からヘルプも自動で作られます。だれかがtimelog --helpと実行すると、OptionParserはちょうど次のように表示して、プログラムを終了します:
puts parser.helpインストールできるツールには、決まったフォルダー構成と.gemspecファイルがあります:
timelog/
├── lib/timelog.rb # the code
├── bin/timelog # the command (#!/usr/bin/env ruby)
├── test/test_timelog.rb
├── timelog.gemspec # name, version, author, files
├── Gemfile # dependencies (Bundler)
└── Rakefile # tasks: rake test$ bundle install # fetches deps, writes Gemfile.lock
$ rake test # runs the tests
$ gem build timelog.gemspec
$ gem install timelog-0.1.0.gem
$ timelog report --week # your tool, everywhere!終了コードも忘れずに。失敗したときはexit 1で終わらせれば、ツールを呼び出したスクリプトがエラーに気づけます。
課題:OptionParserを使って
parse_argv(argv)を書きましょう。対応するのは--weekと--format FORMAT(デフォルトは"text")です。戻り値はハッシュ{ command:, week:, format: }で、commandには残った引数の最初のものが入ります。require "optparse"
# def parse_argv(argv)
# options = { week: false, format: "text" }
# ...
# end