timelog as a real tool
On your machine, programs start in the terminal: timelog add "ProjectX" --from 08:30. Everything after the program name arrives as a string array in ARGV. For clean parsing there's OptionParser from the standard library – here we practice with hand-built arrays:
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 plucks out the options and returns what remains – here the command "report". On top of that you get help for free, built from the descriptions: if someone runs timelog --help, OptionParser prints exactly this and ends the program:
puts parser.helpAn installable tool has a fixed structure and a .gemspec file:
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!Don't forget exit codes: exit 1 on failure, so scripts notice your errors.
Look it up: OptionParser · OptionParser tutorial
Task: Write
parse_argv(argv) with OptionParser: it supports --week and --format FORMAT (default "text"). It returns a hash { command:, week:, format: }, where command is the first remaining argument.require "optparse"
# def parse_argv(argv)
# options = { week: false, format: "text" }
# ...
# end