How to use getoptlong class in ruby?

I need help using the getoptlong class in Ruby. I need to run the command prog_name.ruby -u -i -s filename. So far I can only execute it with prog_name.ruby -u filename -i filename -s filename.

This is my getoptlong code:

require 'getoptlong' class CommonLog parser = GetoptLong.new parser.set_options(["-h", "--help", GetoptLong::NO_ARGUMENT], ["-u", "--url", GetoptLong::NO_ARGUMENT], ["-i", "--ip", GetoptLong::NO_ARGUMENT], ["-s", "--stat", GetoptLong::NO_ARGUMENT]) begin begin opt,arg = parser.get_option break if not opt case opt when "-h" || "--help" puts "Usage: -u filename" puts "Usage: -i filename" puts "Usage: -s filename" exit when "-u" || "--url" log = CommonLog.new(ARGV[0]) log.urlReport when "-i" || "--ip" log = CommonLog.new(ARGV[0]) log.ipReport when "-s" || "--stat" log = CommonLog.new(ARGV[0]) log.statReport end rescue => err puts "#{err.class()}: #{err.message}" puts "Usage: -h -u -i -s filename" exit end end while 1 if ARGV[0] == nil || ARGV.size != 1 puts "invalid! option and filename required" puts "usage: -h -u -i -s filename" end 
+6
source share
1 answer

I am going to answer, recommending a look at the new β€œ slop β€œ gem. ”This is a wrapper around getoptlong .

You can use gem install slop if you use RVM or sudo gem install slop otherwise.

GetOptLong is very powerful, but although I have used it several times, I still need to view documents every time.

If you want a little more power, with a β€œsimpler to use interface than GetOptLong,” take a look at the Ruby OptionParser . You will need to better develop the logic, but this is a quick transition transforming your code. I had to stub the class for the CommonLog stone, because I do not use it. Important material follows the line pull log from ARGV :

 require 'optparse' class CommonLog def initialize(*args); end def urlReport(); puts "running urlReport()"; end def ipReport(); puts "running ipReport()"; end def statReport(arg); puts "running statReport(#{arg})"; end end log = CommonLog.new(ARGV[0]) OptionParser.new { |opts| opts.banner = "Usage: #{File.basename($0)} -u -i -s filename" opts.on( '-u', '--[no-]url', 'some short text describing URL') do log.urlReport() end opts.on('-i', '--[no-]ip', 'some short text describing IP') do log.ipReport() end opts.on('-s', '--stat FILENAME', 'some short text describing STAT') do |arg| log.statReport(arg) end }.parse! 

Also, as a quick criticism, you are not writing Ruby's idiomatic code:

  • Operators
  • when can be written: when "-h", "--help"
  • if ARGV[0] == nil || ARGV.size != 1 if ARGV[0] == nil || ARGV.size != 1 collapsed. Learn how ARGV and arrays work. Usually for ARGV[0] for nil there will be no more arguments, therefore ARGV.empty? likely to be sufficient.
+10
source

Source: https://habr.com/ru/post/886060/


All Articles