0

I'm attempting to create a default opts list using OptionParser that can be used in separate files that share the same opts. Ex:

File 1:

default = OptionParser.new do |opts|
  opts.banner = "This banner is shared by multiple files"
  opts.on("-d", "--debug [level]", "debug logging level: critical, error, warning, info, debug1, debug2") do |opt|
    $debug_level = opt
  end
end
default.parse!(argv)

File 2:

options = OptionParser.new do |opts|
  opts.on("-v", "--version [release]", "release version") do |opt|
    release = opt
  end
end
options.parse!(argv)

without having to repeat the opts.banner and -d opt in each file, I'd like to be able to have file 2 combine the local opts (-v) with the defaults (banner, -d). Writing it out completely would look like:

options = OptionParser.new do |opts|
  opts.banner = "This banner is shared by multiple files"
  opts.on("-d", "--debug [level]", "debug logging level: critical, error, warning, info, debug1, debug2") do |opt|
    $debug_level = opt
  end
  opts.on("-v", "--version [release]", "release version") do |opt|
    release = opt
  end
end
options.parse!(argv)

I've seen a few things for subcommands and such, but never anything that strictly shows that it's possible to combine opts or use them across files.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Brandon R
  • 3
  • 2
  • Across files, no, because you're creating a new OptionParser. You could always pass an `opts` around, I suppose. – Dave Newton Feb 07 '18 at 20:19

1 Answers1

0

For anyone who needs something similar done I was able to do it the following way:

base.rb:

class Base
    # Defines default arguments for commands
    def defaults(argv, &block)

      options = {}

      option_parser = OptionParser.new do |opts|

        opts.banner = "Usage: Define default usage"
        opts.on("-d", "--debug [level]", "debug logging level: critical, error, warning, info, debug1, debug2") do |opt|
          options["level"] = opt
        end
        opts.on("-v", "--version [release]", "release version") do |opt|
          options["release"] = opt
        end
        yield(opts) if block_given?
      end
      option_parser.parse!(argv)
      return options
    end

command.rb:

class Command < Base
def run(argv)

  options = defaults(argv) do |opts|
    opts.banner = "new banner message"
    opts.on("-t", "--test[value]", "test value") do |opt|
      options["value"] = test
    end
  end

This will require a 'require' or 'require_relative' in order for the Command Class to be able to inherit the Base class, but this works as expected and if you don't need anything from the defaults you can simply use

options = defaults(argv) do
end
Brandon R
  • 3
  • 2