I am using Ruby to execute a code that takes command line arguments. now i trying to use the same program with differnt options so i am putting the options in a file and i want the program to read each line interpret the options and execute the program accordingly.
but i get this error. "C:/Ruby193/lib/ruby/1.9.1/optparse.rb:1348:in block in parse_in_order': undefined method
shift' for "--c execue --query unix --Servername abc123":String (NoMethodError)"
i understand that its reading the file and treating the line as string. but wondering if there is a way to overcome this shift error and treat the line as if it was entered in command prompt. or any better solution.
here is my code.
require 'optparse'
require 'micro-optparse'
# --command execue --query unix command --Servername abc123
f =File.open("list_of_commands.txt", "r")
f.each_line { |line|
line= line.chomp
#line = "--c execue --query unix --Servername abc123"
#line = eval("\"#{line}\"")
puts line
options = {}
OptionParser.new do |opts|
opts.on("-c", "--command result,execue,chart,scpfile", String, "Single command to execute ") do |c|
options[:comd] = c
end
opts.on("-q", "--query remote command, unix command", String, "performs the command on local or remote machine") do |q|
options[:query] = q
end
opts.on("-s", "--servername CHSXEDWDC002 ", String, "server name to execute the command") do |v|
options[:hname] = v
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!(line)
p options
}
the contents of the file are below --c execue --query unix --Servername abc123
i also tried to use micro-optparse but facing same error. any workaround ?
Update: as per suggestion from "@mu is too short" i tried below options. end.parse!("#{Shellwords.shellsplit(line)}") and/or end.parse!(Shellwords.shellsplit(line)). but none of them worked.
i also tried to split the line as array using "line = line.split("\t")" and then end.parse!(line). out put as --c execue --query unix --Servername abc123
but now i get error as block in : invalid option --c execute
Update:#2 looking at the error, the issue is with the wrong parameter(-c. but thanks to user "@mu is too short" for suggesting to use Array.
Update: 3 passing the array only worked for short form of the arguments such as -c but when long form was supplied it failed with invalid argument erorr.
i dont see much documentation on the optparse. i even tried micro-parse but it requres default valuves and its not an option for me :(
The parse!
method wants an array as its argument, not a string. You'll probable want to use Shellwords.shellsplit
rather than String#split
(or similar hand-rolled method) to convert your line
to an array just in case you have to deal with quoting and whatnot. Something like this:
OptionParser.new do |opts|
#...
end.parse!(Shellwords.shellsplit(line))