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.
source share