Cannot get ruby optparse to output opts - ruby

I'm trying to learn how to use optparse to take in command line options however I am having a hard time getting it to function as it shows in the class documentation and any examples I can find online. Specifically when I pass the -h option nothing is coming up. I can output ARGV and its showing that it receives -h but it wont display opts.banner and or any of the opts. What am I missing here?
class TestThing
def self.parse(args)
options = {}
options[:time] = 0
options[:operation] = :add
options[:input_file] = ARGV[-2]
options[:output_file] = ARGV[-1]
optparse = OptionParser.new do |opts|
opts.banner = "Usage:[OPTIONS] input_file output_file"
opts.separator = ""
opts.separator = "Specific Options:"
opts.on('-o', '--operation [OPERATION]', "Add or Subtract time, use 'add' or 'sub'") do |operation|
optopns[:operation] = operation.to_sym
end
opts.on('-t', '--time [TIME]', "Time to be shifted, in milliseconds") do |time|
options[:time] = time
end
opts.on_tail("-h", "--help", "Display help screen") do
puts opts
exit
end
opt_parser.parse!(args)
options
end
end
end

You need to hold onto the results of OptionParser.new and then call parse! on it:
op = OptionParser.new do
# what you have now
end
op.parse!
Note that you'll need to do this outside the block you give to new, like so:
class TestThing
def self.parse(args)
options = {}
options[:time] = 0
options[:operation] = :add
options[:input_file] = ARGV[-2]
options[:output_file] = ARGV[-1]
optparse = OptionParser.new do |opts|
opts.banner = "Usage:[OPTIONS] input_file output_file"
# all the rest of your app
end
optparse.parse!(args)
end
end
(I left your indentation in to make it clearer what I mean, but on a side note, you'll find the code easier to work with if you indent consistently).
Also, you don't need to add -h and --help - OptionParser provides those for you automatically and does exactly what you've implemented them to do.

Related

Check command line argument in Ruby code is present

I want to execute Ruby code if command line argument is present:
ruby sanity_checks.rb --trx-request -e staging_psp -g all
Ruby code:
def execute
command_options = CommandOptionsProcessor.parse_command_options
request_type = command_options[:env]
tested_env = command_options[:trx-request] // check here if flag is present
tested_gateways = gateway_names(env: tested_env, gateway_list: command_options[:gateways])
error_logs = []
if(request_type.nil?)
tested_gateways.each do |gateway|
........
end
end
raise error_logs.join("\n") if error_logs.any?
end
How I can get the argument --trx-request and check is it present?
EDIT:
Command parser:
class CommandOptionsProcessor
def self.parse_command_options
command_options = {}
opt_parser = OptionParser.new do |opt|
opt.banner = 'Usage: ruby sanity_checks.rb [OPTIONS]'
opt.separator "Options:"
opt.on('-e TEST_ENV', '--env TEST_ENV','Set tested environment (underscored).') do |setting|
command_options[:env] = setting
end
opt.on('-g X,Y,Z', '--gateways X,Y,Z', Array, 'Set tested gateways (comma separated, no spaces).') do |setting|
command_options[:gateways] = setting
end
end
opt_parser.parse!(ARGV)
command_options
end
end
Can you advice?
You will need to add a boolean switch option to your OptionParser like so
opt.on('-t','--[no-]trx-request','Signifies a TRX Request') do |v|
# note we used an underscore rather than a hyphen to make this symbol
# easier to access
command_options[:trx_request] = v
end
Then in your execute method you can access this as
command_options[:trx_request]
If you need to have a default value you can add one in the parse_command_options method by setting it outside the OptionParser as command_options[:trx_request] = false

How to get the specified option flag from within OptionParser

I'd like to get the exact option flag that was specified on the command line from within Ruby's OptionParser.
For example, suppose I have the following code:
parser = OptionParser.new {
|opts|
opts.on('-f', '--file FILE', 'filename') {
|arg|
$filename = arg
# Here I'd like to know whether '-f' or '--file' was entered
# on the command line.
}
# ... etc. ...
}
I'd like to know whether the user happened to type '-f' or '--file' on the command line. Is this possible without writing two separate opts.on blocks?
I don't think you can get the flags being passed in when inside the OptionParser.new block. At that point it's too late. However, prior to OptionParser parsing the command-line, it's possible to look and see what's being passed in.
ARGV contains the raw command-line. For instance, if this is the command-line invocation for some code:
foo -i 1 -j 2
then ARGV will contain:
["-i", "1", "-j", "2"]
and, then it becomes pretty easy to grab the flags:
ARGV.grep(/^-/) # => ["-i", "-j"]
There are other OptionParser-like tools for Ruby, and those might let you access the flags being used, but I can't think of a reason I'd ever care to. Looking at your code it seems like you're not understanding how to use OptionParser:
parser = OptionParser.new {
|opts|
opts.on('-f', '--file FILE', 'filename') {
|arg|
$filename = arg
# Here I'd like to know whether '-f' or '--file' was entered
# on the command line.
}
# ... etc. ...
}
Instead of doing it that way, I'd write it:
options = {}
OptionParser.new do |opts|
opts.on('-f', '--file FILE', 'filename') { |arg| options[:filename] = arg }
end.parse!
if options[:filename]
puts 'exists' if File.exist?(options[:filename])
end
Then, later in your code you can check in the options hash to see if either of the -f or --file options was given, and what the value was. That it was one or the other of -f or --file shouldn't ever matter.
If it does then you need to differentiate between the two flags, instead of treating them as if they're aliases:
options = {}
OptionParser.new do |opts|
opts.on('-f', 'filename') { |arg| options[:f] = arg }
opts.on('--file FILE', 'filename') { |arg| options[:file] = arg }
end.parse!
if options[:file] || options[:f]
puts 'exists' if File.exist?(options[:file] || options[:f])
end

Optparse doesn't seem to return ARGV array. Argument Required Error

This is homework and I do not expect you to give me the complete answer.
I'm trying to parse a command line entry such as:
./apacheReport.rb -u testlog.txt
When I enter this:
./apacheReport.rb -u testlog.txt
I get:
Argument required
My code is:
require_relative 'CommonLog'
require 'optparse'
# puts ARGV.inspect
optparser = OptionParser.new
optU = false
optI = false
optS = false
optH = false
optparser.banner = "apacheReport.rb [options] filename"
optparser.parse!
rescue => m
puts m.message
puts optparser
exit
end
if ARGV.length < 1
puts "Argument required"
exit
end
userInputFile = ARGV[0]
userInputFile.to_s
file = CommonLog.new(userInputFile)
It should parse the leftover portion of the command into ARGV[0] then should store it as userInputFile and then create a CommonLog object using the file as the constructor. At that point I call the methods that were specified in the command.
It seems that for some reason my ARGV is not being returned. I'm not sure what the issue is.
Ruby's OptionParser is easy to use, but you have to puzzle through the documentation. Here's a little example that'd be useful for your code:
require 'optparse'
options = {}
OptionParser.new do |opt|
opt.on('-u', '--use_this FILE', 'Use this file') { |o| options[:use_this] = o }
end.parse!
options will contain the flags. In this case, if you pass in -u foo, options[:use_this] will be foo.
Save that and try running it without and with a parameter. Also try running it with just a -h flag.
You can search StackOverflow for more answers where I was dealing with OptionParser.
It's hard to tell what's wrong since you code doesn't seem to be working at the moment. The problem may be that the parse! method removes found options from ARGV. So when you write:
optparser.parse!
It removes your two parameters (-u testlog.txt) and this code always fails:
if ARGV.length < 1
puts "Argument required"
exit
end
Instead of looking at ARGV, you need to set up optparser correctly. Perhaps something like:
optparser = OptionParser.new do |opts|
opts.banner = "apacheReport.rb [options] filename"
opts.on("-u", "--u-short-for-this", "Whatever u stands for") do |u|
optU = u
end
end
Then optU will be true only if the user passed -u and the filename will be in ARGV[0].

How to generate OptionParser require arguments

The code below works, but I am manually raising argument errors for the required arguments using fetch, when I want to build the required arguments into the native OptionParser sytax for required parameters:
# ocra script.rb -- --type=value
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("--type [TYPE]",String, [:gl, :time], "Select Exception file type (gl, time)") do |t|
options["type"] = t
end
opts.on("--company [TYPE]",String, [:jaxon, :doric], "Select Company (jaxon, doric)") do |t|
options["company"] = t
end
end.parse!
opts = {}
opts['type'] = options.fetch('type') do
raise ArgumentError,"no 'type' option specified as a parameter (gl or time)"
end
opts['company'] = options.fetch('company') do
raise ArgumentError,"no 'company' option specified as a parameter (doric or jaxon)"
end
There's a similar question with an answer that may help you:
"How do you specify a required switch (not argument) with Ruby OptionParser?"
In short: there doesn't seem to be a way to make an option required (they are called options after all).
There is an OptionParser::MissingArgument exception that you could raise rather than the ArgumentError you're currently throwing.
Faced with the same situation, I ended up with an option like this. If not all of my mandatory options are provided, output the user-friendly help text generated by OptionParser based on my defined options. Feels cleaner than throwing an exception and printing a stack trace to the user.
options = {}
option_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} --data-dir DATA_DIR [options]"
# A non-mandatory option
opts.on('-p', '--port PORT', Integer, 'Override port number') do |v|
options[:port] = v
end
# My mandatory option
opts.on('-d', '--data-dir DATA_DIR', '[Mandatory] Specify the path to the data dir.') do |d|
options[:data_dir] = d
end
end
option_parser.parse!
if options[:data_dir].nil?
puts option_parser.help
exit 1
end

Ruby Options parser not reading command line options

Im trying to use the Ruby builtin options parser
I have this file
File parser.rb
#!/usr/bin/env ruby
require 'optparse'
require 'pp'
class parser
def initialize(args)
#options = Hash.new()
#op = OptionParser.new do |opts|
#options[:verbose] = false
opts.on('-v', '--verbose', 'Output more information') do
#options[:verbose] = true
end
#options[:quick] = false
opts.on( '-q', '--quick', 'Perform the task quickly' ) do
#options[:quick] = true
end
#options[:logfile] = nil
opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do|file|
#options[:logfile] = file
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
#options[:sID] = "-1"
opts.on('-sID', '--senderID', 'Sender ID used by device') do |sID|
#options[:sID] = sID
end
#options[:rID] = "-1"
opts.on('-rID', '--receiverID', 'Receiver ID used by device') do |rID|
#options[:rID] = rID
end
#op.parse!
#op
end
def getOptionsHash
#options
end
then Im trying to use this class in the file below
#!/usr/bin/env ruby
# Setup Bundler
require 'rubygems'
require 'bundler/setup'
require_relative 'parser'
#Variables in the options hash in parser.rb
op = Parser.new(ARGV)
pp op.getOptionsHash()
when I run this on the command line without args it uses default values:
./push_test.rb
I get the following output:
{:verbose=>false,
:quick=>false,
:logfile=>nil,
:sID=>"-1",
:rID=>"-1",
}
when I run this on the command line with args:
./push_test.rb -sID "33"
I get the following output:
{:verbose=>false,
:quick=>false,
:logfile=>nil,
:sID=>"ID",
:rID=>"-1",
}
Why is the sID not being set to 33?
Can anyone help please?Ive tried to figure this out but cant make any headway
Seems the short switch has to be a single character -s
./push_test.rb -sID "33"
outputs:
{:verbose=>false, :quick=>false, :logfile=>nil, :sID=>"ID", :rID=>"-1" }
because everything after -s to the first white space will be assigned to :sID, in your case its the word "ID" that follows "-s", hence you are getting :sID =>"ID"
./push_test.rb -s "33" will do the trick.
From the OptParser docs:
Short style switch:: Specifies short style switch which takes a
mandatory, optional or no argument. It's a string of the following
form:
"-xMANDATORY"
"-x[OPTIONAL]"
"-x"
So at specifying switch -sID you define switch -s with argument named ID - something different than you were probably expecting.

Resources