OptionParser
OptionParser类
父类:对象
OptionParser
介绍
OptionParser是一个用于命令行选项分析的类。它比GetoptLong更高级,但也更易于使用,并且是更加面向Ruby的解决方案。
特征
- 参数说明和处理它的代码写在同一个地方。
- 它可以输出选项摘要; 你不需要单独维护这个字符串。
- 非常优雅地指定了可选和强制参数。
- 参数可以自动转换为指定的类。
- Arguments can be restricted to a certain set.All of these features are demonstrated in the examples below. See make_switch for full documentation.Minimal examplerequire 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! p options p ARGVGenerating HelpOptionParser can be used to automatically generate help for the commands you write:require 'optparse' Options = Struct.new(:name) class Parser def self.parse(options) args = Options.new("world") opt_parser = OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| args.name = n end opts.on("-h", "--help", "Prints this help") do puts opts exit end end opt_parser.parse!(options) return args end end options = Parser.parse %w[--help] #=> # Usage: example.rb [options] # -n, --name=NAME Name to say hello to # -h, --help Prints this helpRequired ArgumentsFor options that require an argument, option specification strings may include an option name in all caps. If an option is used without the required argument, an exception will be raised.require 'optparse' options = {} OptionParser.new do |parser| parser.on("-r", "--require LIBRARY", "Require the LIBRARY before executing your script") do |lib| puts "You required #{lib}!" end end.parse!Used:bash-3.2$ ruby optparse-test.rb -r optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) bash-3.2$ ruby optparse-test.rb -r my-library You required my-library!Type CoercionOptionParser supports the ability to coerce command line arguments into objects for us.OptionParser comes with a few ready-to-use kinds of type coercion. They are:
- 日期 - 任何被接受的东西
Date.parse
- 日期时间 - 任何接受的
DateTime.parse
- 时间 - 任何被
Time.httpdate
或接受的东西Time.parse
- URI - 任何被接受的东西
URI.parse
- Shellwords - 任何被接受的东西
Shellwords.shellwords
- 字符串 - 任何非空字符串
- 整数 - 任何整数。将转换八进制。(例如124,-3,040)
- 浮点数 - 任何浮点数。(例如10,3.14,-100E + 13)
- 数字 - 任何整数,浮点数或有理数(1,3.4,1 / 3)
- Decimal
Integer
- 类似Integer
但不是八进制格式。
- Octal
Integer
- 类似的Integer
,但没有十进制格式。
- 十进制数字 - 十进制整数或浮点数。
- TrueClass - 接受'+,是,
true
, - ,no,false',默认为true
- FalseClass - 与之相同
TrueClass
,但默认为false
- 数组 - 用','分隔的字符串(例如1,2,3)
- Regexp - 正则表达式。还包括选项。
我们也可以添加我们自己的强制措施,我们很快就会介绍。
使用内置转换
例如,使用内置Time
转换。其他内置转换的行为方式相同。OptionParser会尝试将参数解析为一个Time
。如果成功,那个时间将被传递给处理程序块。否则,会引发异常。
require 'optparse'
require 'optparse/time'
OptionParser.new do |parser|
parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
p time
end
end.parse!
用过的:
bash-3.2$ ruby optparse-test.rb -t nonsense
... invalid argument: -t nonsense (OptionParser::InvalidArgument)
from ... time.rb:5:in `block in <top (required)>'
from optparse-test.rb:31:in `<main>'
bash-3.2$ ruby optparse-test.rb -t 10-11-12
2010-11-12 00:00:00 -0500
bash-3.2$ ruby optparse-test.rb -t 9:30
2014-08-13 09:30:00 -0400
创建自定义转化
accept
Option
Parser上的方法可以用来创建转换器。它指定每当指定一个类时调用哪个转换块。下面的示例使用它User
在on
处理程序接收它之前获取对象。
require 'optparse'
User = Struct.new(:id, :name)
def find_user id
not_found = ->{ raise "No User Found for id #{id}" }
[ User.new(1, "Sam"),
User.new(2, "Gandalf") ].find(not_found) do |u|
u.id == id
end
end
op = OptionParser.new
op.accept(User) do |user_id|
find_user user_id.to_i
end
op.on("--user ID", User) do |user|
puts user
end
op.parse!
输出:
bash-3.2$ ruby optparse-test.rb --user 1
#<struct User id=1, name="Sam">
bash-3.2$ ruby optparse-test.rb --user 2
#<struct User id=2, name="Gandalf">
bash-3.2$ ruby optparse-test.rb --user 3
optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
完整的例子
以下示例是一个完整的Ruby程序。您可以运行它并查看指定各种选项的效果。这可能是学习功能的最佳方式optparse
。
require 'optparse'
require 'optparse/time'
require 'ostruct'
require 'pp'
class OptparseExample
Version = '1.0.0'
CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
class ScriptOptions
attr_accessor :library, :inplace, :encoding, :transfer_type,
:verbose, :extension, :delay, :time, :record_separator,
:list
def initialize
self.library = []
self.inplace = false
self.encoding = "utf8"
self.transfer_type = :auto
self.verbose = false
end
def define_options(parser)
parser.banner = "Usage: example.rb [options]"
parser.separator ""
parser.separator "Specific options:"
# add additional options
perform_inplace_option(parser)
delay_execution_option(parser)
execute_at_time_option(parser)
specify_record_separator_option(parser)
list_example_option(parser)
specify_encoding_option(parser)
optional_option_argument_with_keyword_completion_option(parser)
boolean_verbose_option(parser)
parser.separator ""
parser.separator "Common options:"
# No argument, shows at tail. This will print an options summary.
# Try it and see!
parser.on_tail("-h", "--help", "Show this message") do
puts parser
exit
end
# Another typical switch to print the version.
parser.on_tail("--version", "Show version") do
puts Version
exit
end
end
def perform_inplace_option(parser)
# Specifies an optional option argument
parser.on("-i", "--inplace [EXTENSION]",
"Edit ARGV files in place",
"(make backup if EXTENSION supplied)") do |ext|
self.inplace = true
self.extension = ext || ''
self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
end
end
def delay_execution_option(parser)
# Cast 'delay' argument to a Float.
parser.on("--delay N", Float, "Delay N seconds before executing") do |n|
self.delay = n
end
end
def execute_at_time_option(parser)
# Cast 'time' argument to a Time object.
parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
self.time = time
end
end
def specify_record_separator_option(parser)
# Cast to octal integer.
parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
"Specify record separator (default \\0)") do |rs|
self.record_separator = rs
end
end
def list_example_option(parser)
# List of arguments.
parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
self.list = list
end
end
def specify_encoding_option(parser)
# Keyword completion. We are specifying a specific set of arguments (CODES
# and CODE_ALIASES - notice the latter is a Hash), and the user may provide
# the shortest unambiguous text.
code_list = (CODE_ALIASES.keys + CODES).join(', ')
parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
"(#{code_list})") do |encoding|
self.encoding = encoding
end
end
def optional_option_argument_with_keyword_completion_option(parser)
# Optional '--type' option argument with keyword completion.
parser.on("--type [TYPE]", [:text, :binary, :auto],
"Select transfer type (text, binary, auto)") do |t|
self.transfer_type = t
end
end
def boolean_verbose_option(parser)
# Boolean switch.
parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
self.verbose = v
end
end
end
#
# Return a structure describing the options.
#
def parse(args)
# The options specified on the command line will be collected in
# *options*.
@options = ScriptOptions.new
@args = OptionParser.new do |parser|
@options.define_options(parser)
parser.parse!(args)
end
@options
end
attr_reader :parser, :options
end # class OptparseExample
example = OptparseExample.new
options = example.parse(ARGV)
pp options # example.options
pp ARGV
Shell执行
对于现代shell(例如bash,zsh等),可以使用shell完成来执行命令行选项。
更多文档
上面的例子应该足以学习如何使用这个类。如果您有任何问题,请在bugs.ruby-lang.org上提交一张票。
常量
DecimalInteger
十进制整数格式,将被转换为整数。
DecimalNumeric
十进制整数/浮点数格式,整数格式转换为整数,浮点格式转换为浮点数。
OctalInteger
Ruby / C像八进制/十六进制/二进制整数格式,要转换为整数。
属性
bannerW
摘要前的标题横幅。
default_argvRW
字符串在默认情况下被解析。
program_nameW
要在错误消息和默认标题中发出的程序名称,默认为$ 0。
releaseW
发布代码
set_bannerW
摘要前的标题横幅。
set_program_nameW
要在错误消息和默认标题中发出的程序名称,默认为$ 0。
set_summary_indentRW
摘要缩进。必须是字符串(或者有+ String方法)。
set_summary_widthRW
摘要的选项列表部分的宽度。必须是数字。
summary_indentRW
摘要缩进。必须是字符串(或者有+ String方法)。
summary_widthRW
摘要的选项列表部分的宽度。必须是数字。
versionW
版
公共类方法
accept(*args, &blk) Show source
请参阅接受。
# File lib/optparse.rb, line 1098
def self.accept(*args, &blk) top.accept(*args, &blk) end
each_const(path, base = ::Object) Show source
# File lib/optparse/version.rb, line 49
def each_const(path, base = ::Object)
path.split(/::|\//).inject(base) do |klass, name|
raise NameError, path unless Module === klass
klass.constants.grep(/#{name}/i) do |c|
klass.const_defined?(c) or next
klass.const_get(c)
end
end
end
getopts(*args) Show source
参阅getopts。
# File lib/optparse.rb, line 1696
def self.getopts(*args)
new.getopts(*args)
end
inc(arg, default = nil) Show source
返回default
根据的递增值arg
。
# File lib/optparse.rb, line 1034
def self.inc(arg, default = nil)
case arg
when Integer
arg.nonzero?
when nil
default.to_i + 1
end
end
new(banner = nil, width = 32, indent = ' ' * 4) { |self| ... } Show source
初始化实例,如果使用块调用,则自行产生。
banner
横幅消息。
width
摘要宽度。
indent
摘要缩进。
# File lib/optparse.rb, line 1053
def initialize(banner = nil, width = 32, indent = ' ' * 4)
@stack = [DefaultList, List.new, List.new]
@program_name = nil
@banner = banner
@summary_width = width
@summary_indent = indent
@default_argv = ARGV
add_officious
yield self if block_given?
end
reject(*args, &blk) Show source
参阅reject.
# File lib/optparse.rb, line 1111
def self.reject(*args, &blk) top.reject(*args, &blk) end
search_const(klass, name) { |klass, cname, const| ... } Show source
# File lib/optparse/version.rb, line 59
def search_const(klass, name)
klasses = [klass]
while klass = klasses.shift
klass.constants.each do |cname|
klass.const_defined?(cname) or next
const = klass.const_get(cname)
yield klass, cname, const if name === cname
klasses << const if Module === const and const != ::Object
end
end
end
show_version(*pkgs) Show source
# File lib/optparse/version.rb, line 4
def show_version(*pkgs)
progname = ARGV.options.program_name
result = false
show = proc do |klass, cname, version|
str = "#{progname}"
unless klass == ::Object and cname == :VERSION
version = version.join(".") if Array === version
str << ": #{klass}" unless klass == Object
str << " version #{version}"
end
[:Release, :RELEASE].find do |rel|
if klass.const_defined?(rel)
str << " (#{klass.const_get(rel)})"
end
end
puts str
result = true
end
if pkgs.size == 1 and pkgs[0] == "all"
self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
unless cname[1] == ?e and klass.const_defined?(:Version)
show.call(klass, cname.intern, version)
end
end
else
pkgs.each do |pkg|
begin
pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
v = case
when pkg.const_defined?(:Version)
pkg.const_get(n = :Version)
when pkg.const_defined?(:VERSION)
pkg.const_get(n = :VERSION)
else
n = nil
"unknown"
end
show.call(pkg, n, v)
rescue NameError
end
end
end
result
end
terminate(arg = nil) Show source
# File lib/optparse.rb, line 1078
def self.terminate(arg = nil)
throw :terminate, arg
end
top() Show source
# File lib/optparse.rb, line 1083
def self.top() DefaultList end
with(*args, &block) Show source
初始化新实例并评估实例上下文中的可选块。参数args
传递给new,参见参数说明。
此方法已被弃用
,其行为对应于旧的新方法。
# File lib/optparse.rb, line 1025
def self.with(*args, &block)
opts = new(*args)
opts.instance_eval(&block)
opts
end
公共实例方法
abort(mesg = $!) Show source
调用超类方法Kernel#abort
# File lib/optparse.rb, line 1192
def abort(mesg = $!)
super("#{program_name}: #{mesg}")
end
accept(*args, &blk) Show source
指示接受指定的类t
。参数字符串被传递到应该转换为所需类的块。
t
参数类说明符,包括Class的任何对象。
pat
参数模式,默认为t
响应匹配。
accept(t, pat, &block)
# File lib/optparse.rb, line 1094
def accept(*args, &blk) top.accept(*args, &blk) end
banner() Show source
摘要前的标题横幅。
# File lib/optparse.rb, line 1136
def banner
unless @banner
@banner = "Usage: #{program_name} [options]"
visit(:add_banner, @banner)
end
@banner
end
base() Show source
主题on_tail。
# File lib/optparse.rb, line 1206
def base
@stack[1]
end
candidate(word) Show source
# File lib/optparse.rb, line 1743
def candidate(word)
list = []
case word
when /\A--/
word, arg = word.split(/=/, 2)
argpat = Completion.regexp(arg, false) if arg and !arg.empty?
long = true
when /\A-(!-)/
short = true
when /\A-/
long = short = true
end
pat = Completion.regexp(word, true)
visit(:each_option) do |opt|
next unless Switch === opt
opts = (long ? opt.long : []) + (short ? opt.short : [])
opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
if /\A=/ =~ opt.arg
opts.map! {|sw| sw + "="}
if arg and CompletingHash === opt.pattern
if opts = opt.pattern.candidate(arg, false, argpat)
opts.map!(&:last)
end
end
end
list.concat(opts)
end
list
end
def_head_option(*opts, &block)
别名为:define_head
def_option(*opts, &block)
别名为:define
def_tail_option(*opts, &block)
别名为:define_tail
define(*opts, &block) Show source
# File lib/optparse.rb, line 1464
def define(*opts, &block)
top.append(*(sw = make_switch(opts, block)))
sw[0]
end
另外别名为:def_option
define_by_keywords(options, meth, **opts) Show source
# File lib/optparse/kwargs.rb, line 4
def define_by_keywords(options, meth, **opts)
meth.parameters.each do |type, name|
case type
when :key, :keyreq
op, cl = *(type == :key ? %w"[ ]" : ["", ""])
define("--#{name}=#{op}#{name.upcase}#{cl}", *opts[name]) do |o|
options[name] = o
end
end
end
options
end
define_head(*opts, &block) Show source
# File lib/optparse.rb, line 1479
def define_head(*opts, &block)
top.prepend(*(sw = make_switch(opts, block)))
sw[0]
end
另外别名为:def_head_option
define_tail(*opts, &block) Show source
# File lib/optparse.rb, line 1493
def define_tail(*opts, &block)
base.append(*(sw = make_switch(opts, block)))
sw[0]
end
另外别名为:def_tail_option
environment(env = File.basename($0, '.*')) Show source
env
分解环境变量或其大写字母,并像shell一样拆分。
env
默认为程序的基本名称。
# File lib/optparse.rb, line 1800
def environment(env = File.basename($0, '.*'))
env = ENV[env] || ENV[env.upcase] or return
require 'shellwords'
parse(*Shellwords.shellwords(env))
end
getopts(*args) Show source
用于getopts.rb的封装方法。
params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option")
# params[:a] = true # -a
# params[:b] = "1" # -b1
# params[:foo] = "1" # --foo
# params[:bar] = "x" # --bar x
# params[:zot] = "z" # --zot Z
# File lib/optparse.rb, line 1661
def getopts(*args)
argv = Array === args.first ? args.shift : default_argv
single_options, *long_options = *args
result = {}
single_options.scan(/(.)(:)?/) do |opt, val|
if val
result[opt] = nil
define("-#{opt} VAL")
else
result[opt] = false
define("-#{opt}")
end
end if single_options
long_options.each do |arg|
arg, desc = arg.split(';', 2)
opt, val = arg.split(':', 2)
if val
result[opt] = val.empty? ? nil : val
define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact)
else
result[opt] = false
define("--#{opt}", *[desc].compact)
end
end
parse_in_order(argv, result.method(:[]=))
result
end
help() Show source
返回选项摘要字符串。
# File lib/optparse.rb, line 1247
def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
另外别名为:to_s
inc(*args) Show source
# File lib/optparse.rb, line 1042
def inc(*args)
self.class.inc(*args)
end
load(filename = nil) Show source
从文件名加载选项filename
。文件不存在时什么也不做。返回是否成功加载。
filename
默认为程序的基本名称,不带目录后缀〜/ .options。
# File lib/optparse.rb, line 1780
def load(filename = nil)
begin
filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
rescue
return false
end
begin
parse(*IO.readlines(filename).each {|s| s.chomp!})
true
rescue Errno::ENOENT, Errno::ENOTDIR
false
end
end
make_switch(opts, block = nil) Show source
从参数创建一个OptionParser :: Switch。解析后的参数值被传递给给定的块,在那里它可以被处理。
在OptionParser的开始部分查看一些完整的示例。
opts
可以包括以下内容:
参数风格:
以下之一:
:NONE, :REQUIRED, :OPTIONAL
参数模式:
可接受的选项参数格式必须用#accept或#accept或Regexp预定义。如果不存在,这可以出现一次或者以String形式分配,否则会导致ArgumentError。例子:
Float, Time, Array
可能的参数值:
哈希或数组。
[:text, :binary, :auto]
%w[iso-2022-jp shift_jis euc-jp utf8 binary]
{ "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
长型开关:
指定采用强制参数,可选参数或无参数的长型开关。这是一个如下形式的字符串:
"--switch=MANDATORY" or "--switch MANDATORY"
"--switch[=OPTIONAL]"
"--switch"
短式开关:
指定采用强制,可选或无参数的短式开关。这是一个如下形式的字符串:
"-xMANDATORY"
"-x[OPTIONAL]"
"-x"
还有一个匹配字符范围的特殊形式(不是全套正则表达式):
"-[a-z]MANDATORY"
"-[a-z][OPTIONAL]"
"-[a-z]"
参数风格和描述:
可以使用这个单独的参数,而不是直接在switch参数中指定强制参数或可选参数。
"=MANDATORY"
"=[OPTIONAL]"
描述:
选项的描述字符串。
"Run verbosely"
转会:
处理器分析的参数值。要么给出一个块,要么传递一个Proc或Method作为参数。
# File lib/optparse.rb, line 1331
def make_switch(opts, block = nil)
short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
ldesc, sdesc, desc, arg = [], [], []
default_style = Switch::NoArgument
default_pattern = nil
klass = nil
q, a = nil
has_arg = false
opts.each do |o|
# argument class
next if search(:atype, o) do |pat, c|
klass = notwice(o, klass, 'type')
if not_style and not_style != Switch::NoArgument
not_pattern, not_conv = pat, c
else
default_pattern, conv = pat, c
end
end
# directly specified pattern(any object possible to match)
if (!(String === o || Symbol === o)) and o.respond_to?(:match)
pattern = notwice(o, pattern, 'pattern')
if pattern.respond_to?(:convert)
conv = pattern.method(:convert).to_proc
else
conv = SPLAT_PROC
end
next
end
# anything others
case o
when Proc, Method
block = notwice(o, block, 'block')
when Array, Hash
case pattern
when CompletingHash
when nil
pattern = CompletingHash.new
conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
else
raise ArgumentError, "argument pattern given twice"
end
o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
when Module
raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
when *ArgumentStyle.keys
style = notwice(ArgumentStyle[o], style, 'style')
when /^--no-([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
not_pattern, not_conv = search(:atype, o) unless not_style
not_style = (not_style || default_style).guess(arg = a) if a
default_style = Switch::NoArgument
default_pattern, conv = search(:atype, FalseClass) unless default_pattern
ldesc << "--no-#{q}"
(q = q.downcase).tr!('_', '-')
long << "no-#{q}"
nolong << q
when /^--\[no-\]([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--[no-]#{q}"
(o = q.downcase).tr!('_', '-')
long << o
not_pattern, not_conv = search(:atype, FalseClass) unless not_style
not_style = Switch::NoArgument
nolong << "no-#{o}"
when /^--([^\[\]=\s]*)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--#{q}"
(o = q.downcase).tr!('_', '-')
long << o
when /^-(\[\^?\]?(?:[^\\]]|\.)*\])(.+)?/
q, a = $1, $2
o = notwice(Object, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
else
has_arg = true
end
sdesc << "-#{q}"
short << Regexp.new(q)
when /^-(.)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
sdesc << "-#{q}"
short << q
when /^=/
style = notwice(default_style.guess(arg = o), style, 'style')
default_pattern, conv = search(:atype, Object) unless default_pattern
else
desc.push(o)
end
end
default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
if !(short.empty? and long.empty?)
if has_arg and default_style == Switch::NoArgument
default_style = Switch::RequiredArgument
end
s = (style || default_style).new(pattern || default_pattern,
conv, sdesc, ldesc, arg, desc, block)
elsif !block
if style or pattern
raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
end
s = desc
else
short << pattern
s = (style || default_style).new(pattern,
conv, nil, nil, arg, desc, block)
end
return s, short, long,
(not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
nolong
end
new() { |self| ... } Show source
推一个新的列表。
# File lib/optparse.rb, line 1213
def new
@stack.push(List.new)
if block_given?
yield self
else
self
end
end
on(*opts, &block) Show source
添加选项开关和处理程序。有关参数的解释,请参阅make_switch。
# File lib/optparse.rb, line 1473
def on(*opts, &block)
define(*opts, &block)
self
end
on_head(*opts, &block) Show source
像使用on一样添加选项开关,但总结起来。
# File lib/optparse.rb, line 1487
def on_head(*opts, &block)
define_head(*opts, &block)
self
end
on_tail(*opts, &block) Show source
像使用on一样添加选项开关,但在摘要尾部。
# File lib/optparse.rb, line 1501
def on_tail(*opts, &block)
define_tail(*opts, &block)
self
end
order(*argv, into: nil, &nonopt) Show source
argv
按顺序分析命令行参数。当给出一个块时,每个非选项参数都会被产生。
返回argv
未解析的剩余部分。
# File lib/optparse.rb, line 1520
def order(*argv, into: nil, &nonopt)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
order!(argv, into: into, &nonopt)
end
order!(argv = default_argv, into: nil, &nonopt) Show source
与order相同,但破坏性地删除开关。非选项参数保留在argv
。
# File lib/optparse.rb, line 1529
def order!(argv = default_argv, into: nil, &nonopt)
setter = ->(name, val) {into[name.to_sym] = val} if into
parse_in_order(argv, setter, &nonopt)
end
parse(*argv, into: nil) Show source
argv
当设置环境变量POSIXLY_CORRECT时,按顺序分析命令行参数,否则按置换模式分析。
# File lib/optparse.rb, line 1634
def parse(*argv, into: nil)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
parse!(argv, into: into)
end
parse!(argv = default_argv, into: nil) Show source
与解析相同,但破坏性地移除开关。非选项参数保留在argv
。
# File lib/optparse.rb, line 1643
def parse!(argv = default_argv, into: nil)
if ENV.include?('POSIXLY_CORRECT')
order!(argv, into: into)
else
permute!(argv, into: into)
end
end
permute(*argv, into: nil) Show source
argv
在排列模式下解析命令行参数并返回非选项参数列表。
# File lib/optparse.rb, line 1614
def permute(*argv, into: nil)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
permute!(argv, into: into)
end
permute!(argv = default_argv, into: nil) Show source
与排列相同,但破坏性地移除开关。非选项参数保留在argv
。
# File lib/optparse.rb, line 1623
def permute!(argv = default_argv, into: nil)
nonopts = []
order!(argv, into: into, &nonopts.method(:<<))
argv[0, 0] = nonopts
argv
end
program_name() Show source
要在错误消息和默认标题中发出的程序名称,默认为$ 0。
# File lib/optparse.rb, line 1148
def program_name
@program_name || File.basename($0, '.*')
end
reject(*args, &blk) Show source
指示拒绝指定的类参数。
t
参数类说明符,包括Class的任何对象。
reject(t)
# File lib/optparse.rb, line 1107
def reject(*args, &blk) top.reject(*args, &blk) end
release() Show source
发布代码
# File lib/optparse.rb, line 1173
def release
@release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
end
remove() Show source
删除最后一个表。
# File lib/optparse.rb, line 1225
def remove
@stack.pop
end
separator(string) Show source
总结添加分隔符。
# File lib/optparse.rb, line 1510
def separator(string)
top.append(string, nil, nil)
end
summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk) Show source
将选项摘要放入to
并返回to
。如果给出块,则产生每行。
to
输出目的地,必须有方法<<。默认为[]。
width
左侧的宽度,默认为@summary_width。
max
允许左侧的最大长度,默认为width
- 1。
indent
缩进,默认为@summary_indent。
# File lib/optparse.rb, line 1238
def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
visit(:summarize, {}, {}, width, max, indent, &blk)
to
end
terminate(arg = nil) Show source
终止选项解析。可选参数arg
是被推回为第一个非选项参数的字符串。
# File lib/optparse.rb, line 1075
def terminate(arg = nil)
self.class.terminate(arg)
end
to_a() Show source
返回选项摘要列表。
# File lib/optparse.rb, line 1253
def to_a; summarize("#{banner}".split(/^/)) end
to_s()
别名为:help
top() Show source
on / on_head主题,接受/拒绝
# File lib/optparse.rb, line 1199
def top
@stack[-1]
end
ver() Show source
从#program_name,版本和发行版返回版本字符串。
# File lib/optparse.rb, line 1180
def ver
if v = version
str = "#{program_name} #{[v].join('.')}"
str << " (#{v})" if v = release
str
end
end
version() Show source
版
# File lib/optparse.rb, line 1166
def version
@version || (defined?(::Version) && ::Version)
end
warn(mesg = $!) Show source
调用超类方法Kernel#warn
# File lib/optparse.rb, line 1188
def warn(mesg = $!)
super("#{program_name}: #{mesg}")
end
私有实例方法
complete(typ, opt, icase = false, *pat) Show source
完成缩短的长型选项开关并返回一对规范开关和开关描述符OptionParser :: Switch。
typ
搜索表。
opt
搜索键。
icase
如果为真则搜索不区分大小写。
pat
完成的可选模式。
# File lib/optparse.rb, line 1732
def complete(typ, opt, icase = false, *pat)
if pat.empty?
search(typ, opt) {|sw| return [sw, opt]} # exact match or...
end
raise AmbiguousOption, catch(:ambiguous) {
visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
raise InvalidOption, opt
}
end
notwice(obj, prv, msg) Show source
检查参数是否给出两次,在这种情况下引发一个ArgumentError。仅从OptionParser#开关调用。
obj
新的论点。
prv
以前指定的参数。
msg
异常消息。
# File lib/optparse.rb, line 1263
def notwice(obj, prv, msg)
unless !prv or prv == obj
raise(ArgumentError, "argument #{msg} given twice: #{obj}",
ParseError.filter_backtrace(caller(2)))
end
obj
end
search(id, key) { |k| ... } Show source
key
在@stack中搜索id
散列并返回或得出结果。
# File lib/optparse.rb, line 1715
def search(id, key)
block_given = block_given?
visit(:search, id, key) do |k|
return block_given ? yield(k) : k
end
end
visit(id, *args, &block) Show source
遍历@stack,id
使用args
和发送每个元素方法block
。
# File lib/optparse.rb, line 1704
def visit(id, *args, &block)
@stack.reverse_each do |el|
el.send(id, *args, &block)
end
nil
end