Ruby idioms for using command line options

I am trying to pick up ruby ​​by porting a medium-sized perl program (not OO). One of my personal idioms is setting these parameters:

use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later ... $opt_v && print "something interesting\n"; 

In perl, I kind of brush my teeth and let $ opt_v be (efficiently) global.

In ruby, a more or less exact equivalent would be

 require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end 

where $ opt_verbose is global that classes can access. When classes are aware of global flags like this, it seems ... er ... wrong. What is an OO-idiomatic way to do this?

  • Let the main procedure take care of all the materials associated with the option and ask the classes to simply return to it something that it decides how to deal with it?
  • Should classes implement optional behavior (for example, know how to be verbose) and set the mode using attr_writer view?

updated: thanks for the answers suggesting optparse, but I should have made it clearer that this is not how to handle the command-line options that I ask, but more of the relationship between command-line options that effectively set the global state of the program and classes, which ideally should be independent of these kinds of things.

+4
source share
3 answers

A back, I stumbled upon this blog post (Todd Wert), who introduced a rather long skeleton for command line scripts in Ruby, His skeleton uses a hybrid approach in which application code is encapsulated in an application class that is created and then executed by calling a method "run" on the application object. This allowed us to save the parameters in the instance variable of the class so that all methods in the application object could access them without exposing them to other objects that could be used in the script.

I would be inclined to use this method, where the parameters are contained in one object and use either attr_writers or parameter parameters when calling the method to transfer the corresponding parameters to any additional objects. Thus, any code contained in external classes can be isolated from the parameters themselves - no need to worry about naming variables in the main routine from the thingy class if your parameters are set using thingy.verbose=true attr_writer or thingy.process(true) .

+3
source

The optparse library is part of the standard distribution, so you can use it without requiring any third-party materials.

I did not use it personally, but the rails seem to use it widely and so does rspec , which, I think, is a pretty solid vote of confidence

This example from rails script/console seems to show how to use it quite easily and nicely

+2
source

first hit on google for " ruby command line options - this is an article about Trollop , which seems like a good tool for this job.

+1
source

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


All Articles