-
Notifications
You must be signed in to change notification settings - Fork 36
Medium Example
opts = Optimist::options do
version "cool-script v0.1 (code-name: bananas foster)"
banner "This script is pretty cool."
opt :juice, "use juice"
opt :milk, "use milk"
opt :litres, "quantity of liquid", :default => 2.0
opt :brand, "brand name of the liquid", :type => :string
opt :config, "config file path", :type => String, :required => true
opt :drinkers, "number of people drinking the liquid", :default => 6
end
Optimist::die :drinkers, "must be value a greater than zero" if opts[:drinkers] < 1
Optimist::die :config, "must point to an existing file" unless File.exist?(opts[:config]) if opts[:config]
The banner
directive replaces the default banner with a custom banner.
The version
directive auto-creates a :version
long-option and provides a version message.
$ ./medium_example.rb -h
This script is pretty cool.
-j, --juice use juice
-m, --milk use milk
-l, --litres=<f> quantity of liquid (default: 2.0)
-b, --brand=<s> brand name of the liquid
-c, --config=<s> config file path
-d, --drinkers=<i> number of people drinking the liquid (default: 6)
-v, --version Print version and exit
-h, --help Show this message
$ ./medium_example.rb -v
cool-script v0.1 (code-name: bananas foster)
Types are given for some options. Other types are implied from the given default. Also see Option Types.
Setting :required => true
on the opt
will require a user to set that that option on the command-line. This applies to any set of command-line options except when help or version are requested
./medium_example.rb ## no options given
Error: option --config must be specified.
Optimist::die
can be used to form fatal error messages when conditions are not met.
$ ./medium_example.rb -d 1 -c foo.txt
Error: argument --config must point to an existing file.
$ ./medium_example.rb -d 0 -c foo.txt
Error: argument --drinkers must be value greater than zero.
A limited amount of dependency and conflict resolution can be used in Optimist::options
opts = Optimist::options do
version "cool-script v0.2 (code-name: key-lime-pie)"
banner "This script is pretty cool."
opt :juice, "use juice"
opt :fruit, "fruit used to make the juice", :type => :string
opt :milk, "use milk"
opt :beer, "use beer"
conflicts :milk, :juice, :beer
depends :fruit, :juice
end
conflicts
requires :milk
, :juice
and :beer
to be mutually exclusive options.
depends
requires :juice
and :fruit
to be given if either of them are given.
$ ./medium_example_2.rb --juice --milk
Error: --milk conflicts with --juice.
$ ./medium_example_2.rb --juice --milk --beer
Error: --milk conflicts with --juice.
$ ./medium_example_2.rb --juice --beer
Error: --juice conflicts with --beer.
$ ./medium_example_2.rb --fruit
Error: --fruit requires --juice.
$ ./medium_example_2.rb --juice
Error: --juice requires --fruit.