Add popular subcommand-style option parsing to Ruby's stdlib OptionParser class
Ruby
Switch branches/tags
Nothing to show
Clone or download
bjeanes Merge pull request #5 from jasonkarns/stdlib-tests
Subcommand breaks StdLib OptionParser tests
Latest commit 078199e Apr 21, 2017

README.md

optparse-subcommand

Build Status

This gem extends Ruby's standard library OptionParser class to allow popular subcommand-style tools (e.g. git).

Usage

A new method subcommand is added to the OptionParser instance allowing you to define an action to occur when that subcommand is detected as an argument.

The subcommand method takes a block which yields a new OptionParser instance. Simply define your option parsing recursively for all subcommands.

Example:

require 'optparse/subcommand' # Also requires 'optparse'
require 'ostruct'

options                = OpenStruct.new
options.verbose        = false
options.action         = nil
options.action_options = OpenStruct.new

parser = OptionParser.new do |opts|
  opts.on '-v', '--[no-]verbose' do |verbose|
    options.verbose = verbose
  end

  opts.subcommand 'foo' do |foo|
    options.action = :foo

    foo.on '-x' do
      options.action_options.x = true
    end
  end
end

parser.parse(%w[-v foo -x]) # or ARGV, whatever...

options # => #<OpenStruct verbose=true, action=:foo, action_options=#<OpenStruct x=true>>

License

See LICENSE file in this directory.