timelog come strumento vero
Sul tuo computer i programmi si avviano nel terminale: timelog add "ProjectX" --from 08:30. Tutto ciò che segue il nome del programma arriva come array di stringhe in ARGV. Per un'analisi pulita c'è OptionParser della libreria standard – qui ci esercitiamo con array costruiti a mano:
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 estrae le opzioni e restituisce ciò che resta – qui il comando "report". In più ottieni gratis un aiuto, costruito dalle descrizioni: se qualcuno esegue timelog --help, OptionParser stampa esattamente questo e termina il programma:
puts parser.helpUno strumento installabile ha una struttura fissa e un file .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!Non dimenticare i codici di uscita: exit 1 in caso di errore, così gli script si accorgono dei tuoi errori.
parse_argv(argv) con OptionParser: supporta --week e --format FORMAT (predefinito "text"). Restituisce un hash { command:, week:, format: }, dove command è il primo argomento rimasto.require "optparse"
# def parse_argv(argv)
# options = { week: false, format: "text" }
# ...
# end