Module: Trollop
- Defined in:
- lib/trollop/trollop.rb
Overview
lib/trollop.rb – trollop command-line processing library
- Author
-
William Morgan (mailto: [email protected])
- Copyright
-
Copyright 2007 William Morgan
- License
-
GNU GPL version 2
Defined Under Namespace
Classes: CommandlineError, HelpNeeded, Parser, VersionNeeded
Constant Summary collapse
- VERSION =
"1.10.2"
- FLOAT_RE =
Regex for floating point numbers
/^-?((\d+(\.\d+)?)|(\.\d+))$/
- PARAM_RE =
Regex for parameters
/^-(-|\.$|[^\d\.])/
Class Method Summary collapse
-
.die(arg, msg = nil) ⇒ Object
Informs the user that their usage of ‘arg’ was wrong, as detailed by ‘msg’, and dies.
-
.options(args = ARGV, *a, &b) ⇒ Object
The top-level entry method into Trollop.
Class Method Details
.die(arg, msg = nil) ⇒ Object
Informs the user that their usage of ‘arg’ was wrong, as detailed by ‘msg’, and dies. Example:
do
opt :volume, :default => 0.0
end
die :volume, "too loud" if opts[:volume] > 10.0
die :volume, "too soft" if opts[:volume] < 0.1
In the one-argument case, simply print that message, a notice about -h, and die. Example:
do
opt :whatever # ...
end
Trollop::die "need at least one filename" if ARGV.empty?
682 683 684 685 686 687 688 689 690 |
# File 'lib/trollop/trollop.rb', line 682 def die arg, msg=nil if msg $stderr.puts "Error: argument --#{@p.specs[arg][:long]} #{msg}." else $stderr.puts "Error: #{arg}." end $stderr.puts "Try --help for help." exit(-1) end |
.options(args = ARGV, *a, &b) ⇒ Object
The top-level entry method into Trollop. Creates a Parser object, passes the block to it, then parses args
with it, handling any errors or requests for help or version information appropriately (and then exiting). Modifies args
in place. Returns a hash of option values.
The block passed in should contain zero or more calls to opt
(Parser#opt), zero or more calls to text
(Parser#text), and probably a call to version
(Parser#version).
Example:
require 'trollop'
opts = Trollop:: do
opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
end
p opts # returns a hash: { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
See more examples at trollop.rubyforge.org.
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 |
# File 'lib/trollop/trollop.rb', line 644 def args = ARGV, *a, &b @p = Parser.new(*a, &b) begin vals = @p.parse args args.clear @p.leftovers.each { |l| args << l } vals rescue CommandlineError => e $stderr.puts "Error: #{e.}." $stderr.puts "Try --help for help." exit(-1) rescue HelpNeeded @p.educate exit rescue VersionNeeded puts @p.version exit end end |