Can Optionparser Skip Unknown Options, to Be Processed Later in a Ruby Program

Can OptionParser skip unknown options, to be processed later in a Ruby program?

Assuming the order in which the parsers will run is well defined, you can just store the extra options in a temporary global variable and run OptionParser#parse! on each set of options.

The easiest way to do this is to use a delimiter like you alluded to. Suppose the second set of arguments is separated from the first by the delimiter --. Then this will do what you want:

opts = OptionParser.new do |opts|
# set up one OptionParser here
end

both_args = $*.join(" ").split(" -- ")
$extra_args = both_args[1].split(/\s+/)
opts.parse!(both_args[0].split(/\s+/))

Then, in the second code/context, you could do:

other_opts = OptionParser.new do |opts|
# set up the other OptionParser here
end

other_opts.parse!($extra_args)

Alternatively, and this is probably the "more proper" way to do this, you could simply use OptionParser#parse, without the exclamation point, which won't remove the command-line switches from the $* array, and make sure that there aren't options defined the same in both sets. I would advise against modifying the $* array by hand, since it makes your code harder to understand if you are only looking at the second part, but you could do that. You would have to ignore invalid options in this case:

begin
opts.parse
rescue OptionParser::InvalidOption
puts "Warning: Invalid option"
end

The second method doesn't actually work, as was pointed out in a comment. However, if you have to modify the $* array anyway, you can do this instead:

tmp = Array.new

while($*.size > 0)
begin
opts.parse!
rescue OptionParser::InvalidOption => e
tmp.push(e.to_s.sub(/invalid option:\s+/,''))
end
end

tmp.each { |a| $*.push(a) }

It's more than a little bit hack-y, but it should do what you want.

Suppress short arguments with OptionParser

Just drop the short form:

require 'optparse'

OptionParser.new do |opts|
opts.on("--dangerous-option", "Set dangerous option") do |v|
puts "dangerous option set to #{v}"
end
end.parse!

 

$ ruby foo.rb -h
Usage: foo [options]
--dangerous-option Set dangerous option

$ ruby foo.rb --dangerous-option
dangerous option set to true

Printing list of only some options using Ruby OptionParser

You could redefine the option --help for your need.

require 'optparse'

#create parsers
opts = OptionParser.new()
opts.banner = "Usage: example.rb [options]"
opts.separator("test optparse with --help[=full]")
opts.on("-v", "--[no-]verbose", "Run verbosely") { |v|
puts "->Verbose ist #{v.inspect}"
}
opts.on("-r", "--repeat REPEAT", "Repeat REPEAT times") { |v|
puts "->Repeat ist #{v.inspect}"
}

#Define your own --help
opts.on("-h", "--help [HELP]", "Help") { |v|
case v
when 'full' #write original help
puts opts.help
when nil, '' #write script specific help
puts opts.banner
opts.summarize([], opts.summary_width ) { |helpline|
#make your own decision on each helpline
#~ puts helpline #puts each line
puts helpline unless helpline =~ /-v/ #ignore -v
}
else
puts opts.banner
puts <<helpmessage
Undefined --help option. Please use 'full' or no option
#{File.basename(__FILE__)} --help
#{File.basename(__FILE__)} --help=full
helpmessage
end
}

opts.parse!

In this version, --help shows all options, but not -v. You may make your own selection - or write a complete different help.

How to default to information if none is given using optparse

I figured out that by adding brackets around the INPUT I can provide the option to provide input examples:

require 'optparse'

OPTIONS = {}

OptionParser.new do |opts|
opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
end.parse!

def say_hello
puts "Hello #{OPTIONS[:type]}"
end

case
when OPTIONS[:type]
say_hello
else
puts "Hello World"
end

Output:

C:\Users\bin\ruby\test_folder>ruby opt.rb -t
Hello World

C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello

So if I do this:

require 'optparse'

OPTIONS = {}

OptionParser.new do |opts|
opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
end.parse!

def say_hello
puts "Hello #{OPTIONS[:type]}"
puts
puts OPTIONS[:type]
end

case
when OPTIONS[:type]
say_hello
else
puts "Hello World"
puts OPTIONS[:type] unless nil; puts "No value given"
end

I can output the information provided, or when there's no information provided I can output No value given:

C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello

hello

C:\Users\bin\ruby\test_folder>ruby opt.rb -t
Hello World

No value given

OptionParser throwing 'Missing Argument' for no reasons

You can't use a two letter switch like that. With

opts.on('-m', '--markdown', 'Use Markdown Syntax') do

it works fine. See Short style switch under OptionParser documentation

Can ruby's GetOptLong process spaces in option arguments?

Pretty sure you can just pass in your unix commands as a string and execute them from within your script.. so something like:

#getoptlong.rb

require 'getoptlong'

opts = GetoptLong.new(
[ '--unix', GetoptLong::OPTIONAL_ARGUMENT ]
)

opts.each do |opt, arg|
case opt
when '--unix'
puts `#{arg}`
end
end

and execute the script with something like:

ruby getOptLong.rb --unix "netstat -an | grep '61613'"

OptionParser with subcommands

The lines with the error:

global.order!
command = ARGV.shift
subcommands[command].order!

If global.order! uses all of ARGV, then command is nil. So... check for that.

global.order!
command = ARGV.shift
unless command
STDERR.puts "ERROR: no subcommand"
STDERR.puts global # prints usage
exit(-1)
end
subcommands[command].order!


Related Topics



Leave a reply



Submit